unity 拖拽UI

我们经常会使用拖拽UI的效果,untiy 为拖拽事件也提供了现成的API,我们只要简单的实现几个接口即可

我们用两种方式来实现拖拽代码,一种是使用MonoBehaviour里的方法,一种是实现UI事件接口,但不论是那种方法,拖拽的逻辑都是没有区别的。以下为拖拽核心代码

	//这是一个偏移量,如果没有这个偏移量,UI会直接吸附到鼠标的位置
   private Vector3 offset = new Vector3();

	//这是拖拽的代码
	transform.position = Input.mousePosition - offset; 

实现一:使用MonoBehaviour
这要求我们需要为UI设置一个2D碰撞盒,鼠标只有在碰撞盒内拖动才会触发事件,需要注意UI的一个像素就是1米,所以碰撞盒需要做的非常大,例如一个长宽都是100的图片,碰撞盒的size 是100*100
在这里插入图片描述
代码如下

    private void OnMouseDown()
    {
    
    
        print("开始拖拽");
        //按下鼠标计算鼠标和自己轴心的偏移量
        offset = Input.mousePosition - transform.position;
    }
    private void OnMouseDrag()
    {
    
    
        print("鼠标拖拽");
        transform.position = Input.mousePosition - offset; //拖拽
    }
    private void OnMouseUp()
    {
    
    
        print("结束拖拽");
    }

实现二:使用接口
需要先引入UI事件命名空间

using UnityEngine.EventSystems;

需要注意,想让UI事件生效,场景里必须有EventSystem这个物体,如果你发现UI有反应,可能是误删了EventSystem,可以在新建的UI里新建一个

实现接口及拖拽代码如下

public class DragPanel : MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IDragHandler
{
    
    
    
    private Vector3 offset = new Vector3();

    public void OnPointerDown(PointerEventData eventData)
    {
    
    
        print("开始拖拽");
        //按下鼠标计算鼠标和自己轴心的偏移量
        offset = Input.mousePosition - transform.position;
    }
    public void OnDrag(PointerEventData eventData)
    {
    
    
        print("鼠标拖拽");
        transform.position = Input.mousePosition - offset; //拖拽
    }
    public void OnPointerUp(PointerEventData eventData)
    {
    
    
		print("结束拖拽");
    }
}

开始拖拽和结束拖拽也可以使用 IBeginDragHandler,IEndDragHandler 这两个接口来实现

猜你喜欢

转载自blog.csdn.net/weixin_44568736/article/details/129038147