75 lines
2.4 KiB
C#
75 lines
2.4 KiB
C#
using UnityEngine;
|
||
using UnityEngine.EventSystems;
|
||
using UnityEngine.UI;
|
||
|
||
public class UIDragItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
|
||
{
|
||
private RectTransform rectTransform; // UI 图片的 RectTransform
|
||
private CanvasGroup canvasGroup; // CanvasGroup 用于处理拖拽时的透明度
|
||
private Vector2 startPosition; // 拖拽开始时的初始位置
|
||
private Vector2 offset; // 鼠标相对于 UI 中心点的偏移量
|
||
|
||
void Start()
|
||
{
|
||
// 获取 RectTransform 组件
|
||
rectTransform = GetComponent<RectTransform>();
|
||
|
||
// 添加 CanvasGroup 组件(如果不存在)
|
||
canvasGroup = GetComponent<CanvasGroup>();
|
||
if (canvasGroup == null)
|
||
{
|
||
canvasGroup = gameObject.AddComponent<CanvasGroup>();
|
||
}
|
||
}
|
||
|
||
// 开始拖拽时调用
|
||
public void OnBeginDrag(PointerEventData eventData)
|
||
{
|
||
// 记录初始位置
|
||
startPosition = rectTransform.anchoredPosition;
|
||
|
||
// 计算鼠标相对于 UI 中心点的偏移量
|
||
Vector2 localPoint;
|
||
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out localPoint))
|
||
{
|
||
offset = localPoint;
|
||
}
|
||
|
||
// 降低透明度,表示拖拽状态
|
||
canvasGroup.alpha = 0.6f;
|
||
|
||
// 禁用 Raycast 目标,防止拖拽时阻挡其他 UI 事件
|
||
canvasGroup.blocksRaycasts = false;
|
||
}
|
||
|
||
// 拖拽过程中调用
|
||
public void OnDrag(PointerEventData eventData)
|
||
{
|
||
// 将屏幕坐标转换为 UI 父对象的本地坐标
|
||
Vector2 screenPoint = eventData.position;
|
||
Vector2 localPoint;
|
||
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
|
||
rectTransform.parent as RectTransform, // 父对象(Canvas 或 Panel)
|
||
screenPoint, // 屏幕坐标
|
||
eventData.pressEventCamera, // 相机(Canvas 的渲染模式决定)
|
||
out localPoint // 输出的本地坐标
|
||
))
|
||
{
|
||
// 根据鼠标位置和偏移量更新 UI 的位置
|
||
rectTransform.anchoredPosition = localPoint - offset;
|
||
}
|
||
}
|
||
|
||
// 结束拖拽时调用
|
||
public void OnEndDrag(PointerEventData eventData)
|
||
{
|
||
// 恢复透明度
|
||
canvasGroup.alpha = 1.0f;
|
||
|
||
// 启用 Raycast 目标
|
||
canvasGroup.blocksRaycasts = true;
|
||
|
||
// 如果需要,可以将 UI 图片重置到初始位置
|
||
// rectTransform.anchoredPosition = startPosition;
|
||
}
|
||
} |