其他分享
首页 > 其他分享> > unity实现鼠标拖拽物体的方法

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;
        }
    }
    
}

标签:Distance,Mouseposition,gameObject,transform,unity,position,Input,拖拽,鼠标
来源: https://blog.csdn.net/The1stChen/article/details/120418338