Unity学习笔记 鼠标点击拖拽等

本文介绍了Unity中实现UI元素拖动的三种方法。第一种是使用内置的OnMouseXXX()系列方法,需要目标对象有碰撞体。第二种是通过EventTrigger组件添加事件监听。第三种是实现IPointerDownHandler、IDragHandler等接口来处理拖放操作。拖动过程中,可以获取pointerEventData中的delta和pointerDrag属性来跟踪拖动状态。

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

1.使用unity内置方法 OnMouseXXX(),需要目标有碰撞体。适合2D贴图和3D场景使用。ui的拖动使用下面两种方法。

 /// <summary>
		    /// Called when the mouse enters the GUIElement or Collider.
		    /// </summary>
		    void OnMouseEnter ()
		
		    /// <summary>
		    /// Called when the mouse is not any longer over the GUIElement or Collider.
		    /// </summary>
		    void OnMouseExit ()
		
		    /// <summary>
		    /// OnMouseDown is called when the user has pressed the mouse button while
		    /// over the GUIElement or Collider.
		    /// </summary>
		    void OnMouseDown ()
		
		    /// <summary>
		    /// OnMouseUp is called when the user has released the mouse button.
		    /// </summary>
		    void OnMouseUp ()
		
		        /// <summary>
		    /// OnMouseDrag is called when the user has clicked on a GUIElement or Collider
		    /// and is still holding down the mouse.
		    /// </summary>
		    void OnMouseDrag ()
		
		       /// <summary>
		    /// Called every frame while the mouse is over the GUIElement or Collider.
		    /// </summary>
		    void OnMouseOver ()
		
		 /// <summary>
		    /// OnMouseUpAsButton is only called when the mouse is released over
		    /// the same GUIElement or Collider as it was pressed.
		    /// </summary>
		    void OnMouseUpAsButton ()
		    //松开鼠标时,仅当鼠标在按下时所在的 Collider 上时,才调用 OnMouseUpAsButton。

2.使用EventTrigger 给ui物体添加EventTrigger,在其中选择需要的事件并添加相应的响应函数
在这里插入图片描述

3.通过接口实现拖拽

	using UnityEngine;
	using UnityEngine.EventSystems;
	public class DragByInterface : MonoBehaviour, IPointerDownHandler, IDragHandler, IBeginDragHandler, IEndDragHandler
	{
	    public void OnPointerDown (PointerEventData PointerEventData) { }
	    public void OnBeginDrag (PointerEventData PointerEventData) { }
	    public void OnDrag (PointerEventData PointerEventData) { }
	    public void OnEndDrag (PointerEventData PointerEventData) { }
	}
补充:OnBeginDrag 和 OnEndDrag 依赖于OnDrag。
	pointerEventData中包含一系列信息,包括距上一帧的偏移量,当前拖拽的物体等
	var offset = pointerEventData.delta;
    var dragTarget = pointerEventData.pointerDrag;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值