赞
踩
IBeginDragHandler、IDragHandler 和 IEndDragHandler 是 Unity 引擎中的三个接口,用于处理 UI 元素的拖动事件。
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Drag : MonoBehaviour ,IBeginDragHandler, IDragHandler,IEndDragHandler { //场景中的canvas public Canvas canv; RectTransform dragObjRect = null; //拖拽的ui public RectTransform dragUI; //是否能拖拽 public bool canDrag = false; void Start() { dragObjRect = canv.transform as RectTransform; } 开始拖拽 public void OnBeginDrag(PointerEventData eventData) { //这里可以写一些过滤条件,比如只拖拽tag为item的物体 if (eventData.pointerEnter.tag == "item") { canDrag = true; dragUI = eventData.pointerEnter.GetComponent<RectTransform>(); } else { canDrag = false; } } //拖拽中 public void OnDrag(PointerEventData eventData) { if (!canDrag) return; Vector3 globalMousePos; if (RectTransformUtility.ScreenPointToWorldPointInRectangle (dragObjRect, eventData.position, eventData.pressEventCamera, out globalMousePos)) { dragUI.position = globalMousePos; dragUI.rotation = dragObjRect.rotation; CheckPos(); } } //拖拽结束 public void OnEndDrag(PointerEventData eventData) { canDrag = false; dragUI = null; } //检查位置,如果拖拽超出指定区域,则重新赋值 void CheckPos() { Vector2 pos = dragUI.anchoredPosition; if (pos.x <= -150) { pos.x = -150; } else if (pos.x >= 150) { pos.x = 150; } else if (pos.y >= 40) { pos.y = 40; } else if (pos.y <= -40) { pos.y = -40; } dragUI.anchoredPosition = pos; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。