如果你只想要一个指向目标的箭头:
Transform camera = Camera.main.transform;
Transform target = Target.transform;
Vector3 relativePosition = target.position - camera.position;
Vector3 targetRelative = Vector3.ProjectOnPlane(relativePosition, camera.forward);
float angle = Angle360(camera.up, targetRelative, camera.forward);
Compass.transform.rotation = Quaternion.Euler(0, 0, angle);
角度函数为:
float Angle360(Vector3 from, Vector3 to, Vector3 normal)
{
float dot = Vector3.Dot(from, to);
float det = Vector3.Dot(normal, Vector3.Cross(from, to));
return Mathf.Atan2(det, dot)*Mathf.Rad2Deg;
}
以下是在世界空间中获取指南针方向的方法:
在XZ平面上投影相机方向和目标位置
Transform camera = Camera.main.transform;
Transform target = Target.transform;
Vector3 cameraWorldDirXZ = Vector3.ProjectOnPlane(camera.forward, Vector3.up).normalized;
Vector3 targetWorldDirXZ = Vector3.ProjectOnPlane(target.position, Vector3.up).normalized;
cameraWorldDirXZ 和targetWorldDirXZ 之间的夹角就是你的指南针的角度。
但我认为这不会像你想象的那样。这为您提供了围绕y 轴旋转camera.forward 向量以面向目标所需的角度。如果您围绕camera.forward 旋转,则不会更改camera.forward 向量或y 轴,因此指南针不会改变。
您可能想在本地空间尝试指南针。为此,您将其投影到相机 XZ 平面上:
Vector3 cameraLocalDirXZ = camera.forward;
Vector3 targetLocalDirXZ = Vector3.ProjectOnPlane(target.position, camera.up).normalized;
cameraLocalDirXZ 和 targetLocalDirXZ 之间的角度再次是您的指南针的角度。这为您提供了围绕camera.up 旋转camera.forward 以面对目标所需的角度。请注意,当您围绕camera.forward 旋转时,它会改变camera.up,因此它会改变指南针方向。