DragPanel.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.EventSystems;
  4. using System.Collections;
  5. public class DragPanel : MonoBehaviour, IPointerDownHandler, IDragHandler {
  6. private Vector2 originalLocalPointerPosition;
  7. private Vector3 originalPanelLocalPosition;
  8. private RectTransform panelRectTransform;
  9. private RectTransform parentRectTransform;
  10. void Awake () {
  11. panelRectTransform = transform.parent as RectTransform;
  12. parentRectTransform = panelRectTransform.parent as RectTransform;
  13. }
  14. public void OnPointerDown (PointerEventData data) {
  15. originalPanelLocalPosition = panelRectTransform.localPosition;
  16. RectTransformUtility.ScreenPointToLocalPointInRectangle (parentRectTransform, data.position, data.pressEventCamera, out originalLocalPointerPosition);
  17. }
  18. public void OnDrag (PointerEventData data) {
  19. if (panelRectTransform == null || parentRectTransform == null)
  20. return;
  21. Vector2 localPointerPosition;
  22. if (RectTransformUtility.ScreenPointToLocalPointInRectangle (parentRectTransform, data.position, data.pressEventCamera, out localPointerPosition)) {
  23. Vector3 offsetToOriginal = localPointerPosition - originalLocalPointerPosition;
  24. panelRectTransform.localPosition = originalPanelLocalPosition + offsetToOriginal;
  25. }
  26. ClampToWindow ();
  27. }
  28. // Clamp panel to area of parent
  29. void ClampToWindow () {
  30. Vector3 pos = panelRectTransform.localPosition;
  31. Vector3 minPosition = parentRectTransform.rect.min - panelRectTransform.rect.min;
  32. Vector3 maxPosition = parentRectTransform.rect.max - panelRectTransform.rect.max;
  33. pos.x = Mathf.Clamp (panelRectTransform.localPosition.x, minPosition.x, maxPosition.x);
  34. pos.y = Mathf.Clamp (panelRectTransform.localPosition.y, minPosition.y, maxPosition.y);
  35. panelRectTransform.localPosition = pos;
  36. }
  37. }