You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.6 KiB

  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3. using UnityEngine.UI;
  4. [RequireComponent(typeof(Image))]
  5. public class Dragable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
  6. {
  7. protected RectTransform m_DraggingPlane;
  8. public virtual void OnBeginDrag(PointerEventData eventData)
  9. {
  10. var canvas = FindInParents<Canvas>(gameObject);
  11. if (canvas == null)
  12. return;
  13. m_DraggingPlane = canvas.transform as RectTransform;
  14. transform.SetParent(m_DraggingPlane,false);
  15. SetDraggedPosition(eventData);
  16. }
  17. public virtual void OnDrag(PointerEventData data)
  18. {
  19. SetDraggedPosition(data);
  20. }
  21. protected virtual void SetDraggedPosition(PointerEventData data)
  22. {
  23. var rt = transform as RectTransform;
  24. Vector3 globalMousePos;
  25. if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, data.position, data.pressEventCamera, out globalMousePos))
  26. {
  27. rt.position = globalMousePos;
  28. rt.rotation = m_DraggingPlane.rotation;
  29. }
  30. }
  31. public virtual void OnEndDrag(PointerEventData eventData)
  32. {
  33. }
  34. static public T FindInParents<T>(GameObject go) where T : Component
  35. {
  36. if (go == null) return null;
  37. var comp = go.GetComponent<T>();
  38. if (comp != null)
  39. return comp;
  40. Transform t = go.transform.parent;
  41. while (t != null && comp == null)
  42. {
  43. comp = t.gameObject.GetComponent<T>();
  44. t = t.parent;
  45. }
  46. return comp;
  47. }
  48. }