Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.EventSystems;
- public class DraggableControl : MonoBehaviour,
- IPointerDownHandler, IPointerUpHandler, IDragHandler
- {
- public GameObject parent;
- public Canvas canvas;
- private bool _isDragging;
- private Vector3 _offset;
- // Start is called before the first frame update
- void Start()
- {
- }
- public void OnPointerDown(PointerEventData eventData)
- {
- _isDragging = true;
- _offset = eventData.position - new Vector2(parent.transform.position.x, parent.transform.position.y);
- }
- public void OnPointerUp(PointerEventData eventData)
- {
- _isDragging = false;
- }
- public void OnDrag(PointerEventData eventData)
- {
- if (_isDragging)
- {
- Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f) - _offset;
- parent.transform.position = position;
- /**
- * TODO Tomorrow
- * Move the two getcomponent calls up to the OnPointerDown handler, so we only call it once while
- * the playeris dragging the ui element, instead of every frame that it is dragging.
- */
- ClampToWindow(
- position,
- parent.GetComponent<RectTransform>(),
- canvas.GetComponent<RectTransform>());
- }
- }
- private void ClampToWindow(Vector3 mousePosition, RectTransform parentRect, RectTransform canvasRect)
- {
- parentRect.transform.position = mousePosition;
- Vector3 pos = parentRect.localPosition;
- Vector3 minPosition = canvasRect.rect.min - parentRect.rect.min;
- Vector3 maxPosition = canvasRect.rect.max - parentRect.rect.max;
- pos.x = Mathf.Clamp(parentRect.localPosition.x, minPosition.x, maxPosition.x);
- pos.y = Mathf.Clamp(parentRect.localPosition.y, minPosition.y, maxPosition.y);
- parentRect.localPosition = pos;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement