unity实现鼠标拖拽物体的方法

 这三个方法都是没有优化过的方法,鼠标点到物体的时候物体的中心点会跳到鼠标点的位置,从一开始写的方法三理解之后慢慢删代码最后变成了方法一。。。。。。。。

public class 箭头 : MonoBehaviour
{
    private bool 拖拽 = true;
    // Start is called before the first frame update
    void Start()
    {
     
    }

    // Update is called once per frame
    void Update()
    {

方法一::::::::::::::::::::::::::::::::::::::::::::::
        Vector3 Mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Mouseposition.z = 0;
        float Distance = (this.gameObject.transform.position - Mouseposition).magnitude;
        if (Input.GetMouseButton(0) && (Distance < 1.5f))
        {
            this.gameObject.transform.position = Mouseposition;
        }


方法二::::::::::::::::::::::::::::::::::::::::::::::
        Vector3 Mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Mouseposition.z = 0;
        if (Input.GetMouseButton(0))
        {
            float Distance = (this.gameObject.transform.position - Mouseposition).magnitude;
            if (Distance < 1.5f)
            {
                this.gameObject.transform.position = Mouseposition;
            }
        }


方法三::::::::::::::::::::::::::::::::::::::::::::::
        Vector3 Mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Mouseposition.z = 0;
        if (Input.GetMouseButton(0))
        {
            float Distance = (this.gameObject.transform.position - Mouseposition).magnitude;
            if (Distance < 1.5f)
            {
                拖拽 = true;
            }
        }
        else
        {
            拖拽 = false;
        }
        if (拖拽)
        {
            this.gameObject.transform.position = Mouseposition;
        }
    }
    
}

上一篇:总结Unity查找物体的几种方法


下一篇:Unity 反转法线,在 Hierarchy 视图对象的快捷菜单中增加 Flip Mesh Normals(反转网格法线)项