65 lines
2.0 KiB
C#
65 lines
2.0 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; // 拖拽开始时的初始位置
|
||
|
||
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;
|
||
|
||
// 降低透明度,表示拖拽状态
|
||
canvasGroup.alpha = 0.6f;
|
||
|
||
// 禁用 Raycast 目标,防止拖拽时阻挡其他 UI 事件
|
||
canvasGroup.blocksRaycasts = false;
|
||
}
|
||
|
||
// 拖拽过程中调用
|
||
public void OnDrag(PointerEventData eventData)
|
||
{
|
||
// 将屏幕坐标转换为 UI 坐标
|
||
Vector2 screenPoint = eventData.position;
|
||
RectTransformUtility.ScreenPointToLocalPointInRectangle(
|
||
rectTransform.parent as RectTransform, // 父对象(Canvas 或 Panel)
|
||
screenPoint, // 屏幕坐标
|
||
eventData.pressEventCamera, // 相机(Canvas 的渲染模式决定)
|
||
out Vector2 localPoint // 输出的本地坐标
|
||
);
|
||
|
||
// 更新 UI 图片的位置
|
||
rectTransform.anchoredPosition = localPoint;
|
||
}
|
||
|
||
// 结束拖拽时调用
|
||
public void OnEndDrag(PointerEventData eventData)
|
||
{
|
||
// 恢复透明度
|
||
canvasGroup.alpha = 1.0f;
|
||
|
||
// 启用 Raycast 目标
|
||
canvasGroup.blocksRaycasts = true;
|
||
|
||
// 如果需要,可以将 UI 图片重置到初始位置
|
||
// rectTransform.anchoredPosition = startPosition;
|
||
}
|
||
} |