UGUI跟隨滑鼠移動
阿新 • • 發佈:2018-12-15
using UnityEngine; using UnityEngine.EventSystems; public class DragUIMove : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler,IEndDragHandler{ public RectTransform canvas; private RectTransform imgRect; Vector2 offset = new Vector3(); private bool UICanMove = false; //判斷當前的拖拽是否可以讓整個UI移動,滑鼠在其他按鈕上時拖拽,避免造成錯誤。 // Use this for initialization void Awake() { imgRect = GetComponent<RectTransform>(); } public void OnPointerDown(PointerEventData eventData) { Vector2 mouseDown = eventData.position; Vector2 mouseUguiPos = new Vector2(); bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, mouseDown, eventData.enterEventCamera, out mouseUguiPos); if (isRect) { offset = imgRect.anchoredPosition - mouseUguiPos; UICanMove = true; } } public void OnDrag(PointerEventData eventData) { if(UICanMove) { Vector2 mouseDrag = eventData.position; Vector2 uguiPos = new Vector2(); bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, mouseDrag, eventData.enterEventCamera, out uguiPos); if (isRect) { imgRect.anchoredPosition = offset + uguiPos; } } } public void OnPointerUp(PointerEventData eventData) { offset = Vector2.zero; UICanMove = false; } public void OnEndDrag(PointerEventData eventData) { offset = Vector2.zero; UICanMove = false; } }