Unity 实现拖拽UI功能

记录一下学习过程中的知识点

要实现UI拖拽功能,我们只需要实现相关的UI事件接口

比如Button组件的单击功能就是通过实现接口IPointerClickHandler

我们可以通过拖拽接口,实现拖拽的功能

因为Input.mousePosition是屏幕坐标,而UI的位置却是世界坐标,所以我们需要把鼠标位置转换到世界坐标,然后将返回的位置信息给拖拽的对象就可以了

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ImageDrap : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler
{
    private RectTransform rectTransform;
    // Start is called before the first frame update
    void Start()
    {
        rectTransform = GetComponent<RectTransform>();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("开始拖拽");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 pos;
        RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, eventData.position, eventData.enterEventCamera, out pos);
        rectTransform.position = pos;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("结束拖拽");
    }

}

发布了9 篇原创文章 · 获赞 2 · 访问量 2714

猜你喜欢

转载自blog.csdn.net/u014288698/article/details/88207627