【Unity3D】拖拽3D物体

需求:如题
在做UI拖拽的时候用了IDragHandler接口,非常好用,但是这个接口是继承自IEventSystemHandler,而所有UnityEngine.EventSystems中的类都继承自EventSystems.UIBehaviour,所以这个接口只对canvas和UI起作用。

所以想到了对于拖拽3D物体通常用的函数OnMouseDrag(),但是实际在我们的工程中使用的时候并不是很舒服,所以采用Input和raycast检测的方式。
在要拖拽的物体A(有collider,有rigidbody)上挂的脚本Ascript中:

bool isDragging = false;
Vector3 screenSpace;
Vector3 resPos;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        isDragging = true;
        screenSpace = Camera.main.WorldToScreenPoint(transform.position);
        //do something...
    }

    if (isDragging)
    {
        //keep track of the mouse position
        var curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
        //convert the screen mouse position to world point and adjust with offset
        resPos = Camera.main.ScreenToWorldPoint(curScreenSpace);
    }

    if (Input.GetMouseButtonUp(0))
    {
        isDragging = false;
        //do something...
    }
}

在要把A物体放置到的地点B上(比如说Plane)也要有collider,在B上挂的脚本BScript中:

void Update()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit))
    {
        //do something...
    }
}

你可能感兴趣的:(鼠标事件)