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.

71 lines
1.9 KiB

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