基于鼠标瞄准Unity3d
我正在制作炮弹射击游戏。 这是一个简短的代码,我在计算瞄准方向。
Vector3 mousePos = Input.mousePosition; mousePos.z = thisTransform.position.z - camTransform.position.z; mousePos = mainCamera.ScreenToWorldPoint (mousePos); Vector3 force = mousePos - thisTransform.position; force.z = force.magnitude;
这适用于球和角度(0,0,0)。 但是当角度改变时,我无法向正确的方向射击。
假设球和相机在右侧看45度,相同的代码不起作用。
当前代码假定两者都是角度(0,0,0)。 所以在上面提到的情况下,投掷方向总是错误的。
我想把球扔向任何方向。 但假设它为0角并相应地投掷。
在这种情况下使用Camera.ScreenToWorldPoint
是错误的。
你应该对飞机使用光线投射。 这是一个没有不必要数学的演示:
Raycasting为您提供了优势,您无需猜测用户点击的“深度”( z
坐标)。
这是上面的简单实现:
/// /// Gets the 3D position of where the mouse cursor is pointing on a 3D plane that is /// on the axis of front/back and up/down of this transform. /// Throws an UnityException when the mouse is not pointing towards the plane. /// /// The 3d mouse position Vector3 GetMousePositionInPlaneOfLauncher () { Plane p = new Plane(transform.right, transform.position); Ray r = Camera.main.ScreenPointToRay(Input.mousePosition); float d; if(p.Raycast(r, out d)) { Vector3 v = r.GetPoint(d); return v; } throw new UnityException("Mouse position ray not intersecting launcher plane"); }
Demonstation: https : //github.com/chanibal/Very-Generic-Missle-Command