更新UI拖拽组件 支持鼠标与UI中心点的偏移计算
This commit is contained in:
parent
45cae04aa6
commit
5012e405ec
@ -7,6 +7,7 @@ public class UIDragItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDr
|
||||
private RectTransform rectTransform; // UI 图片的 RectTransform
|
||||
private CanvasGroup canvasGroup; // CanvasGroup 用于处理拖拽时的透明度
|
||||
private Vector2 startPosition; // 拖拽开始时的初始位置
|
||||
private Vector2 offset; // 鼠标相对于 UI 中心点的偏移量
|
||||
|
||||
void Start()
|
||||
{
|
||||
@ -27,6 +28,13 @@ public class UIDragItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDr
|
||||
// 记录初始位置
|
||||
startPosition = rectTransform.anchoredPosition;
|
||||
|
||||
// 计算鼠标相对于 UI 中心点的偏移量
|
||||
Vector2 localPoint;
|
||||
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out localPoint))
|
||||
{
|
||||
offset = localPoint;
|
||||
}
|
||||
|
||||
// 降低透明度,表示拖拽状态
|
||||
canvasGroup.alpha = 0.6f;
|
||||
|
||||
@ -37,17 +45,19 @@ public class UIDragItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDr
|
||||
// 拖拽过程中调用
|
||||
public void OnDrag(PointerEventData eventData)
|
||||
{
|
||||
// 将屏幕坐标转换为 UI 坐标
|
||||
// 将屏幕坐标转换为 UI 父对象的本地坐标
|
||||
Vector2 screenPoint = eventData.position;
|
||||
RectTransformUtility.ScreenPointToLocalPointInRectangle(
|
||||
Vector2 localPoint;
|
||||
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
|
||||
rectTransform.parent as RectTransform, // 父对象(Canvas 或 Panel)
|
||||
screenPoint, // 屏幕坐标
|
||||
eventData.pressEventCamera, // 相机(Canvas 的渲染模式决定)
|
||||
out Vector2 localPoint // 输出的本地坐标
|
||||
);
|
||||
|
||||
// 更新 UI 图片的位置
|
||||
rectTransform.anchoredPosition = localPoint;
|
||||
out localPoint // 输出的本地坐标
|
||||
))
|
||||
{
|
||||
// 根据鼠标位置和偏移量更新 UI 的位置
|
||||
rectTransform.anchoredPosition = localPoint - offset;
|
||||
}
|
||||
}
|
||||
|
||||
// 结束拖拽时调用
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user