unity 物体拖拽移动

3D物体拖拽移动

1 获取鼠标的屏幕坐标
2 将鼠标坐标与相机y轴方向的值,转换为3d坐标,并将改制赋给跟随鼠标移动对象

void Update () {
     //   Vector3 vp = Camera.main.ScreenToViewportPoint(Input.mousePosition + new Vector3(0, 0, Camera.main.farClipPlane));
        transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0, 0, Camera.main.transform.position.y));


    }

NGUI 鼠标拖拽

参考NGUI示例demo中的Drag代码:Example 11 - Drag & Drop
使用到的类:
UIDragDropItem
UIDragDropRoot 当拖拽超出scrowView时,可以继续显示拖拽对象

使用方法
自己创建一个脚本,继承UIDragDropItem,重写拖拽的事件方法
开始拖拽移动
protected override void OnDragDropStart()
结束拖拽
protected override void OnDragDropRelease (GameObject surface)
正在拖拽
protected override void OnDragDropMove(Vector3 delta)

UGUI 鼠标拖拽

在canvans下面创建一个Image对象,在该对象上面添加一个控制拖拽的脚步

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MyDrag : 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);
    }

    /// 
    /// set position of the dragged game object
    /// 
    /// 
    private void SetDraggedPosition(PointerEventData eventData)
    {
        var rt = gameObject.GetComponent();

        // transform the screen point to world point int rectangle
        Vector3 globalMousePos;
        //把屏幕坐标转换为UGUI对应的坐标
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, eventData.pressEventCamera, out globalMousePos))
        {
            rt.position = globalMousePos;
        }
    }
}

脚步继承3个接口IBeginDragHandler, IDragHandler, IEndDragHandler,分别监听开始拖拽、正在拖拽和拖拽结束三种状态

你可能感兴趣的:(unity-开发)