Unity—实现鼠标拖拽

本文介绍了在Unity中实现鼠标拖拽功能的方法,包括NGUI和UGUI两种方式。NGUI可通过覆写OnDragRelease()轻松实现,而UGUI则需要实现接口并手动更新UI对象坐标,代码简单但需挂载于Canvas下的Image组件上。

鼠标拖拽好像只能用于UI对象,暂时好像是这样的,如有误,我后面会更新。

一:NGUI实现

    NGUI的更简单,只需直接覆写OnDragRelease()方法

//拖拽结束时调用
protected override void OnDragDropRelease(GameObject surface)
{
}

什么都不用写就实现了拖拽。

二、UGUI实现

    UGUI需要实现对应的接口,以及自己更新UI对象的坐标,代码如下:

public class DragTest : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{

    // begin dragging
    public void OnBeginDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    // during dragging
    public void OnDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    // end dragging
    public void OnEndDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    /// <summary>
    /// set position of the dragged game object
    /// </summary>
    /// <param name="eventData"></param>
Unity实现鼠标拖拽移动物体,你可以按照以下步骤操作: 1. **创建组件**: 首先,确保你的游戏对象有一个`Rigidbody`组件用于物理运动,以及`MouseCursor`组件来处理鼠标输入。 2. **添加事件监听**: 在`Update()`或`FixedUpdate()`函数中,检查是否发生鼠标按下事件(`Input.GetMouseButtonDown(0)`)。如果是,存储当前的游戏对象位置和鼠标位置(`Vector3 mousePos = Input.mousePosition;` 和 `transform.position` )。 3. **开始拖动**: 当鼠标按下并保持时,计算鼠标相对于屏幕左上角的偏移量,并将其转换为世界坐标(`Vector3 delta = Camera.main.ScreenToWorldPoint(mousePos) - transform.position;`)。 4. **实时更新**: 每次帧更新时,应用这个偏移量到游戏对象的位置(`transform.position += delta * Time.deltaTime;`),注意这里乘以`Time.deltaTime`是为了让移动更平滑。 5. **鼠标释放结束拖动**: 检查鼠标抬起事件(`Input.GetMouseButtonUp(0)`), 当鼠标松开时停止更新位置,并将游戏对象位置恢复到原始值,关闭拖动模式。 ```csharp void Update() { if (Input.GetMouseButtonDown(0)) { storedPosition = transform.position; dragStartMousePos = Input.mousePosition; } else if (Input.GetMouseButtonUp(0)) { // 结束拖动 transform.position = storedPosition; } else if (Input.GetMouseButton(0)) { Vector3 delta = Camera.main.ScreenToWorldPoint(Input.mousePosition) - dragStartMousePos; transform.position += delta * Time.deltaTime; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值