Advertisement
Krythic

UI Dragging

Jan 15th, 2024
823
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.95 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3.  
  4. public class DraggableControl : MonoBehaviour,
  5.     IPointerDownHandler, IPointerUpHandler, IDragHandler
  6. {
  7.     public GameObject parent;
  8.     public Canvas canvas;
  9.     private bool _isDragging;
  10.     private Vector3 _offset;
  11.  
  12.     // Start is called before the first frame update
  13.     void Start()
  14.     {
  15.  
  16.     }
  17.  
  18.     public void OnPointerDown(PointerEventData eventData)
  19.     {
  20.         _isDragging = true;
  21.         _offset = eventData.position - new Vector2(parent.transform.position.x, parent.transform.position.y);
  22.     }
  23.  
  24.     public void OnPointerUp(PointerEventData eventData)
  25.     {
  26.         _isDragging = false;
  27.     }
  28.  
  29.     public void OnDrag(PointerEventData eventData)
  30.     {
  31.         if (_isDragging)
  32.         {
  33.             Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f) - _offset;
  34.             parent.transform.position = position;
  35.             /**
  36.              * TODO Tomorrow
  37.              * Move the two getcomponent calls up to the OnPointerDown handler, so we only call it once while
  38.              * the playeris dragging the ui element, instead of every frame that it is dragging.
  39.              */
  40.             ClampToWindow(
  41.                 position,
  42.                 parent.GetComponent<RectTransform>(),
  43.                 canvas.GetComponent<RectTransform>());
  44.         }
  45.     }
  46.  
  47.     private void ClampToWindow(Vector3 mousePosition, RectTransform parentRect, RectTransform canvasRect)
  48.     {
  49.         parentRect.transform.position = mousePosition;
  50.         Vector3 pos = parentRect.localPosition;
  51.         Vector3 minPosition = canvasRect.rect.min - parentRect.rect.min;
  52.         Vector3 maxPosition = canvasRect.rect.max - parentRect.rect.max;
  53.         pos.x = Mathf.Clamp(parentRect.localPosition.x, minPosition.x, maxPosition.x);
  54.         pos.y = Mathf.Clamp(parentRect.localPosition.y, minPosition.y, maxPosition.y);
  55.         parentRect.localPosition = pos;
  56.     }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement