using System; using AX.InputSystem; using UnityEngine; using UnityEngine.EventSystems; /// /// UI拖拽脚本,想拖拽谁就挂在谁身上。必须保证该UI有Raycast Target组件,并使其保持开启状态。 /// [RequireComponent(typeof(CreateStaticObjID))] [RequireComponent(typeof(BaseGameObjInfo))] public class OnDragPanel : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler { private RectTransform canvasRect; private RectTransform transRect; private Vector2 localPos; private Vector2 offSet; public bool limit; private Vector2 anchoredPosition; private void Start() { canvasRect = GameObject.Find("Canvas").GetComponent(); transRect = GetComponent(); offSet = localPos = Vector3.zero; anchoredPosition = transRect.anchoredPosition; } public void OnBeginDrag(PointerEventData eventData) { if (eventData.button != PointerEventData.InputButton.Left) return;//不是左键按下就不能拖拽 if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, eventData.position, canvasRect.GetComponent().worldCamera, out localPos)) { offSet = localPos - new Vector2(transRect.localPosition.x, transRect.localPosition.y); InputManager.isDargUI = true; //transform.SetAsLastSibling(); } } public void OnDrag(PointerEventData eventData) { if (eventData.button != PointerEventData.InputButton.Left) return;//不是左键按下就不能拖拽 if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, eventData.position, canvasRect.GetComponent().worldCamera, out localPos)) { transRect.localPosition = localPos - offSet; } } public void OnEndDrag(PointerEventData eventData) { if (eventData.button != PointerEventData.InputButton.Left) return;//不是左键按下就不能拖拽 InputManager.isDargUI = false; if (limit) { //if (OutLimit()) //{ //transRect.anchoredPosition = anchoredPosition; // } OutLimit(); } } void OutLimit() { Vector3 pos = transRect.localPosition; Vector3 minPosition = transform.parent.GetComponent().rect.min - transRect.rect.min; Vector3 maxPosition = transform.parent.GetComponent().rect.max - transRect.rect.max; pos.x = Mathf.Clamp(transRect.localPosition.x, minPosition.x - transRect.rect.width + 50f, maxPosition.x + transRect.rect.width - 50f); pos.y = Mathf.Clamp(transRect.localPosition.y, minPosition.y - transRect.rect.height + 50f, maxPosition.y + transRect.rect.height - 50f); transRect.localPosition = pos; } }