| | 1 | | using UnityEngine; |
| | 2 | | using UnityEngine.EventSystems; |
| | 3 | | using UnityEngine.UI; |
| | 4 | |
|
| | 5 | | public class DragUIHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { |
| | 6 | |
|
| | 7 | | private Vector2 pointerOffset; |
| | 8 | | private RectTransform canvasRectTransform; |
| | 9 | | private RectTransform panelRectTransform; |
| | 10 | | private Vector3 startLocalScale; |
| | 11 | | private Vector2 originalPivot; |
| 0 | 12 | | [SerializeField] private float scaleDownOnBeginDrag = 1f; |
| | 13 | | private bool jumpOneFrame; |
| | 14 | |
|
| | 15 | | public void Start(){ |
| | 16 | |
|
| 0 | 17 | | Canvas canvas = GetComponentInParent<Canvas> (); |
| 0 | 18 | | if(canvas != null){ |
| 0 | 19 | | canvasRectTransform = canvas.transform as RectTransform; |
| 0 | 20 | | panelRectTransform = transform as RectTransform; |
| | 21 | | } |
| 0 | 22 | | startLocalScale = panelRectTransform.localScale; |
| 0 | 23 | | originalPivot = panelRectTransform.pivot; |
| 0 | 24 | | } |
| | 25 | |
|
| | 26 | | #region IBeginDragHandler implementation |
| | 27 | |
|
| | 28 | | public void OnBeginDrag (PointerEventData eventData) |
| | 29 | | { |
| 0 | 30 | | RectTransformUtility.ScreenPointToLocalPointInRectangle (panelRectTransform, eventData.position, eventData.press |
| 0 | 31 | | SetPivot(panelRectTransform, Rect.PointToNormalized(panelRectTransform.rect, localPointerForNewPivot)); |
| 0 | 32 | | panelRectTransform.localScale = startLocalScale * scaleDownOnBeginDrag; |
| 0 | 33 | | RectTransformUtility.ScreenPointToLocalPointInRectangle (panelRectTransform, eventData.position, eventData.press |
| 0 | 34 | | } |
| | 35 | |
|
| | 36 | | #endregion |
| | 37 | |
|
| | 38 | | #region IDragHandler implementation |
| | 39 | |
|
| | 40 | | public void OnDrag (PointerEventData eventData) |
| | 41 | | { |
| 0 | 42 | | if(panelRectTransform == null){ |
| 0 | 43 | | return; |
| | 44 | | } |
| 0 | 45 | | if(RectTransformUtility.ScreenPointToLocalPointInRectangle (canvasRectTransform, eventData.position, eventData.p |
| 0 | 46 | | panelRectTransform.localPosition = localPointerPosition - pointerOffset; |
| | 47 | | } |
| 0 | 48 | | } |
| | 49 | |
|
| | 50 | | #endregion |
| | 51 | |
|
| | 52 | | #region IEndDragHandler implementation |
| | 53 | |
|
| | 54 | | public void OnEndDrag (PointerEventData eventData) |
| | 55 | | { |
| 0 | 56 | | panelRectTransform.localScale = startLocalScale; |
| 0 | 57 | | SetPivot(panelRectTransform, originalPivot); |
| 0 | 58 | | } |
| | 59 | |
|
| | 60 | | #endregion |
| | 61 | |
|
| | 62 | | private void SetPivot(RectTransform target, Vector2 pivot) |
| | 63 | | { |
| 0 | 64 | | if (!target) return; |
| 0 | 65 | | var offset= pivot - target.pivot; |
| 0 | 66 | | offset.Scale(target.rect.size); |
| 0 | 67 | | var wordlPos= target.position + target.TransformVector(offset); |
| 0 | 68 | | target.pivot = pivot; |
| 0 | 69 | | target.position = wordlPos; |
| 0 | 70 | | } |
| | 71 | | } |