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
2.0 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 GameObject m_DraggingIcon;
  8. protected RectTransform m_DraggingPlane;
  9. public virtual void OnBeginDrag(PointerEventData eventData)
  10. {
  11. var canvas = FindInParents<Canvas>(gameObject);
  12. if (canvas == null)
  13. return;
  14. // We have clicked something that can be dragged.
  15. // What we want to do is create an icon for this.
  16. m_DraggingIcon = new GameObject("icon");
  17. m_DraggingIcon.transform.SetParent(canvas.transform, false);
  18. m_DraggingIcon.transform.SetAsLastSibling();
  19. var image = m_DraggingIcon.AddComponent<Image>();
  20. image.sprite = GetComponent<Image>().sprite;
  21. image.SetNativeSize();
  22. m_DraggingPlane = canvas.transform as RectTransform;
  23. SetDraggedPosition(eventData);
  24. }
  25. public virtual void OnDrag(PointerEventData data)
  26. {
  27. if (m_DraggingIcon != null)
  28. SetDraggedPosition(data);
  29. }
  30. protected virtual void SetDraggedPosition(PointerEventData data)
  31. {
  32. var rt = m_DraggingIcon.GetComponent<RectTransform>();
  33. Vector3 globalMousePos;
  34. if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, data.position, data.pressEventCamera, out globalMousePos))
  35. {
  36. rt.position = globalMousePos;
  37. rt.rotation = m_DraggingPlane.rotation;
  38. }
  39. }
  40. public virtual void OnEndDrag(PointerEventData eventData)
  41. {
  42. }
  43. static public T FindInParents<T>(GameObject go) where T : Component
  44. {
  45. if (go == null) return null;
  46. var comp = go.GetComponent<T>();
  47. if (comp != null)
  48. return comp;
  49. Transform t = go.transform.parent;
  50. while (t != null && comp == null)
  51. {
  52. comp = t.gameObject.GetComponent<T>();
  53. t = t.parent;
  54. }
  55. return comp;
  56. }
  57. }