1.新建场景,在场景中创建一个UI的Panel。
2.创建脚本Drag.cs,将脚本附加到Panel上。
using UnityEngine;
using UnityEngine.EventSystems;
public class DragUI : MonoBehaviour,IDragHandler,IBeginDragHandler, IEndDragHandler, IPointerClickHandler
{
private Vector3 offset;//记录初始鼠标与元素的偏移量
bool isDrag = false;//区分点击还是拖拽
public void OnBeginDrag(PointerEventData eventData)
{
offset = transform.position - new Vector3(eventData.position.x, eventData.position.y, transform.position.z);
}
public void OnDrag(PointerEventData eventData)
{
isDrag = true;
transform.position = offset + new Vector3(eventData.position.x, eventData.position.y, transform.position.z);
}
public void OnEndDrag(PointerEventData eventData)
{
isDrag = false;
}
public void OnPointerClick(PointerEventData eventData)
{
if(!isDrag)
{
//点击
}
}
}