DragUI.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3. namespace Rokid.UXR.Components {
  4. public class DragUI : MonoBehaviour, IDragHandler, IEndDragHandler, IBeginDragHandler
  5. {
  6. [SerializeField]
  7. public RectTransform canvas;//得到canvas的ugui坐标
  8. [SerializeField]
  9. public Transform frontParent;
  10. private RectTransform imgRect;
  11. private CanvasGroup canvasGroup;
  12. private Transform oldParent;
  13. private Transform nowParent;
  14. public int sibiling;
  15. private Vector2 offset;//临时记录点击点与UI的相对位置
  16. void Start()
  17. {
  18. //初始化组件
  19. imgRect = GetComponent<RectTransform>();
  20. canvasGroup = GetComponent<CanvasGroup>();
  21. sibiling = transform.GetSiblingIndex();
  22. oldParent = transform.parent;
  23. }
  24. public void OnDrag(PointerEventData eventData)
  25. {
  26. // UnityEngine.RKLog.Info("On Drag");
  27. Vector2 mouseDrag = eventData.position; //当鼠标拖动时的屏幕坐标
  28. Vector2 uguiPos; //用来接收转换后的拖动坐标
  29. bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, mouseDrag, eventData.enterEventCamera, out uguiPos);
  30. if (isRect)
  31. {
  32. //设置图片的ugui坐标与鼠标的ugui坐标保持不变
  33. imgRect.anchoredPosition = offset + uguiPos;
  34. }
  35. }
  36. public void OnBeginDrag(PointerEventData eventData)
  37. {
  38. //开始拖拽
  39. canvasGroup.blocksRaycasts = false;
  40. //这里必须先更换父物体否则,offset会计算出问题
  41. nowParent = transform.parent;
  42. transform.SetParent(frontParent);
  43. Vector2 mouseDown = eventData.position;
  44. Vector2 mouseUguiPos;
  45. bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, mouseDown, eventData.enterEventCamera, out mouseUguiPos);
  46. if (isRect)
  47. {
  48. offset = imgRect.anchoredPosition - mouseUguiPos;
  49. }
  50. }
  51. public void OnEndDrag(PointerEventData eventData)
  52. {
  53. RKLog.Info("On End Drag");
  54. if (eventData.pointerCurrentRaycast.gameObject != null)
  55. {
  56. if (eventData.pointerCurrentRaycast.gameObject.name == "Grid")
  57. {
  58. Transform targetParent = eventData.pointerCurrentRaycast.gameObject.transform;
  59. if (targetParent.childCount > 0)
  60. {
  61. RKLog.Info("Change Position");
  62. //交换位置
  63. Transform target = targetParent.GetChild(0);
  64. target.SetParent(oldParent);
  65. target.localPosition = Vector3.zero;
  66. }
  67. transform.SetParent(targetParent);
  68. transform.localPosition = Vector3.zero;
  69. }
  70. else
  71. {
  72. //返回
  73. transform.SetParent(oldParent);
  74. transform.localPosition = Vector3.zero;
  75. }
  76. }
  77. else
  78. {
  79. //返回
  80. transform.SetParent(oldParent);
  81. transform.localPosition = Vector3.zero;
  82. }
  83. canvasGroup.blocksRaycasts = true;
  84. }
  85. }
  86. }