DragableUi.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.EventSystems;
  6. namespace SoftKitty.MasterCharacterCreator
  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. _dragOffset = DragableRectTransform.InverseTransformPoint(eventData.pointerCurrentRaycast.screenPosition) * DragableRectTransform.localScale.x;
  23. _isDraging = true;
  24. }
  25. }
  26. public void OnDrag(PointerEventData eventData)
  27. {
  28. if (!_parentTransform) _parentTransform = DragableRectTransform.parent.GetComponent<RectTransform>();
  29. if (_isDraging && Dragable)
  30. {
  31. Vector2 localPosition = Vector2.zero;
  32. RectTransformUtility.ScreenPointToLocalPointInRectangle(
  33. _parentTransform,
  34. eventData.position,
  35. null,
  36. out localPosition);
  37. DragableRectTransform.position = _parentTransform.TransformPoint(localPosition - _dragOffset);
  38. }
  39. }
  40. public void OnEndDrag(PointerEventData eventData)
  41. {
  42. _isDraging = false;
  43. }
  44. #endregion
  45. }
  46. }