DragableUi.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.EventSystems;
  6. namespace SoftKitty.InventoryEngine
  7. {
  8. public class DragableUi : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
  9. {
  10. public bool Dragable = true; //Enable dragging
  11. public RectTransform DragableRectTransform; //The RectTransform to Drag
  12. #region Variables
  13. private RectTransform _parentTransform;
  14. private bool _isDraging = false;
  15. private Vector2 _dragOffset;
  16. #endregion
  17. #region Internal Methods
  18. public void OnBeginDrag(PointerEventData eventData)
  19. {
  20. if (Dragable && eventData.button == PointerEventData.InputButton.Left)
  21. {
  22. if (GetComponentInParent<Canvas>().renderMode == RenderMode.ScreenSpaceCamera)
  23. {
  24. _dragOffset = DragableRectTransform.InverseTransformPoint(eventData.pointerCurrentRaycast.worldPosition) - DragableRectTransform.position;
  25. }
  26. else
  27. {
  28. _dragOffset = DragableRectTransform.InverseTransformPoint(eventData.pointerCurrentRaycast.screenPosition) * DragableRectTransform.localScale.x;
  29. }
  30. _isDraging = true;
  31. }
  32. }
  33. public void OnDrag(PointerEventData eventData)
  34. {
  35. if (!_parentTransform) _parentTransform = DragableRectTransform.parent.GetComponent<RectTransform>();
  36. if (_isDraging && Dragable)
  37. {
  38. Vector2 localPosition = Vector2.zero;
  39. RectTransformUtility.ScreenPointToLocalPointInRectangle(
  40. _parentTransform,
  41. eventData.position,
  42. GetComponentInParent<Canvas>().renderMode == RenderMode.ScreenSpaceCamera?GetComponentInParent<Canvas>().worldCamera:null,
  43. out localPosition);
  44. DragableRectTransform.position = _parentTransform.TransformPoint(localPosition - _dragOffset);
  45. }
  46. }
  47. public void OnEndDrag(PointerEventData eventData)
  48. {
  49. _isDraging = false;
  50. }
  51. #endregion
  52. }
  53. }