Unity,UI拖拽(跟随手指移动)

本文介绍了一个Unity中自定义UI拖拽组件的实现方法。通过继承MonoBehaviour并实现IPointerDownHandler等接口,文章详细展示了如何响应鼠标按下、拖动及释放事件,并利用RectTransformUtility将屏幕坐标转换为UI坐标,实现UI元素的平滑拖拽。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class UIDrag : MonoBehaviour, IPointerDownHandler, IDragHandler, IEndDragHandler
{

    #region 字段
    public RectTransform canvas;
    private RectTransform imgRect;
    Vector2 offest = new Vector2();
    #endregion

    private void Start()
    {
        imgRect = this.GetComponent<RectTransform>();
        canvas = this.transform.parent.GetComponent<RectTransform>();
    }

    #region  接口
    public void OnDrag(PointerEventData eventData)
    {
        Vector2 mouseDrag = eventData.position;
        Vector2 uguiPos = new Vector2();

        //RectTransformUtility.ScreenPointToLocalPointInRectangle() 把屏幕坐标转换成UI坐标
        //canvas 为当前物体的父物体的RectTransform
        bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,mouseDrag,eventData.enterEventCamera,out uguiPos);
        if (isRect)
        {
            imgRect.anchoredPosition = offest + uguiPos;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        offest = Vector2.zero;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("按下");
        Vector2 mouseDown = eventData.position;   //鼠标按下时的屏幕坐标
        Vector2 mouseUguiPos = new Vector2();   //返回的UGUI坐标
        bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,mouseDown,eventData.enterEventCamera,out mouseUguiPos);
        if (isRect)
        {
            offest = imgRect.anchoredPosition - mouseUguiPos;     //计算点击在UI上但是没点击在UI正中心
            Debug.Log(offest);
        }
    }

    #endregion
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值