Input.mousePosition与hit.point的区别

xiaoxiao2021-02-28  104

今天是unity3D学习的第三天,学习过程中出现了一个疑问,来源于以下代码片段:

void Update(){ if(Input.GetMouseButtonDown(0))//如果点击了鼠标左键 { //创建一条从摄像机到点击位置的射线,并赋值给ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //如果射线发生物理碰撞(且将碰撞内容赋给hit) if(Physics.Raycast(ray,out hit)) { //实例化子弹(三个参数依次为:子弹刚体,摄像机位置,不旋转) GameObject go = GameObject.Instantiate(prefabBullet, m_Transform.position, Quaternion.identity) as GameObject; //计算从摄像机到撞击点的方向 Vector3 dir = hit.point - m_Transform.position; //发射子弹 go.GetComponent<Rigidbody>().AddForce(dir * 100); } } }

这里用到了两个位置,一个是Input.mousePosition,而另一个是hit.point。这两个位置有什么区别呢? 让我们看一下Input.mousePosition的官方文档https://docs.unity3d.com/ScriptReference/Input-mousePosition.html 这里提到:

The current mouse position in pixel coordinates. (Read Only) The bottom-left of the screen or window is at (0, 0). The top-right of the screen or window is at (Screen.width, Screen.height).

也就是说,Input.mousePosition是我们屏幕的坐标,具备二维特征,无法和我们实质上想要点击的物体产生联系。 在这里我们以摄像头为起点,摄像头至屏幕点击位置为方向,建立了射线ray,进而通过unity3D内置的API,将ray产生的物理碰撞内容赋给hit,再通过hit.point,得到我们真正想要的三维位置。 总结: Input.mousePostion是鼠标落点之于屏幕的位置,并不具备三维联系。 hit.point是射线产生物理碰撞的位置,是游戏场景内的三维坐标。

转载请注明原文地址: https://www.6miu.com/read-2626400.html

最新回复(0)