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.

74 lines
2.2 KiB

5 years ago
5 years ago
5 years ago
  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. m_DraggingIcon.layer = LayerMask.NameToLayer("Ignore Raycast");
  20. var image = m_DraggingIcon.AddComponent<Image>();
  21. image.sprite = GetComponent<Image>().sprite;
  22. image.SetNativeSize();
  23. m_DraggingPlane = canvas.transform as RectTransform;
  24. SetDraggedPosition(eventData);
  25. }
  26. public virtual void OnDrag(PointerEventData data)
  27. {
  28. if (m_DraggingIcon != null)
  29. SetDraggedPosition(data);
  30. }
  31. protected virtual void SetDraggedPosition(PointerEventData data)
  32. {
  33. var rt = m_DraggingIcon.GetComponent<RectTransform>();
  34. Vector3 globalMousePos;
  35. if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, data.position, data.pressEventCamera, out globalMousePos))
  36. {
  37. rt.position = globalMousePos;
  38. rt.rotation = m_DraggingPlane.rotation;
  39. }
  40. }
  41. public virtual void OnEndDrag(PointerEventData eventData)
  42. {
  43. Destroy(m_DraggingIcon);
  44. m_DraggingIcon = null;
  45. }
  46. static public T FindInParents<T>(GameObject go) where T : Component
  47. {
  48. if (go == null) return null;
  49. var comp = go.GetComponent<T>();
  50. if (comp != null)
  51. return comp;
  52. Transform t = go.transform.parent;
  53. while (t != null && comp == null)
  54. {
  55. comp = t.gameObject.GetComponent<T>();
  56. t = t.parent;
  57. }
  58. return comp;
  59. }
  60. }