目录
效果演示
拖拽功能的实现
我们只需要在拖拽时,将鼠标的位置坐标赋给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;
}
}
}
可以看到现在已经可以完成拖拽了,不过这明显不是我们想要的效果。我们希望鼠标和UI的相对位置在拖拽的过程中保持固定,
所以我们需要在开始拖拽时算出UI和鼠标之间的位置偏移量,以后就可以通过鼠标的位置加上偏移量来保证它们的相对位置不变。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unit