目录
效果演示
![](https://i-blog.csdnimg.cn/blog_migrate/e709d22c57b5380a56b658788b02f354.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/91f9876ed178008b78206210516cdb08.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/442743db427aa70d64e17131ff1004f8.gif)
拖拽功能的实现
我们只需要在拖拽时,将鼠标的位置坐标赋给UI即可
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Demo1 : MonoBehaviour, IDragHandler
{
RectTransform rt;
void Start()
{
rt = GetComponent<RectTransform>();
}
public void OnDrag(PointerEventData eventData)
{
// 将屏幕空间上的点转换为位于给定RectTransform平面上的世界空间中的位置
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, eventData.pressEventCamera, out Vector3 globalMousePos))
{
rt.position = globalMousePos;
}
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/2f9e7bb0a753402a81ce3622f0f23dbf.gif)
可以看到现在已经可以完成拖拽了,不过这明显不是我们想要的效果。我们希望鼠标和UI的相对位置在拖拽的过程中保持固定,
所以我们需要在开始拖拽时算出UI和鼠标之间的位置偏移量,以后就可以通过鼠标的位置加上偏移量来保证它们的相对位置不变。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unit