使用Vector3.forward
写作new Vector3(0, 0, 1)的简写。
返回 Unity 自身的前 Z 轴方向。这完全取决于您启动 Unity/您的应用程序时设备的方向,与现实世界坐标无关。
您可能更愿意寻找Compass,它返回您手机的实际方向,例如使用magneticHeading
相对于磁北极的航向。
此属性中的值始终是相对于顶部测量的
当前方向的屏幕。磁北方向
与真正的地理北方并不完全相同 - 要获得准确的
标题,使用trueHeading 属性。
public class Example : MonoBehaviour
{
void Update()
{
// Orient an object to point to magnetic north.
transform.rotation = Quaternion.Euler(0, -Input.compass.magneticHeading, 0);
}
}
或使用trueHeading
相对于地理北极的航向。
此属性中的值始终是相对于顶部测量的
当前方向的屏幕。请注意,如果你想要这个
要包含有效值的属性,您还必须启用位置
调用Input.location.Start()更新。
using UnityEngine;
public class Example : MonoBehaviour
{
void Start()
{
Input.location.Start();
}
void Update()
{
// Orient an object to point northward.
transform.rotation = Quaternion.Euler(0, -Input.compass.trueHeading, 0);
}
}
因此,对于您的用例,您只需使用例如
using UnityEngine;
public enum Heading
{
North,
East,
South,
West
}
public class Example : MonoBehaviour
{
[Header("Debug")]
[SerializeField] [Range(0f, 360f)] private float northHeading;
[Header("OutputValues")]
[SerializeField] private float myHeading;
[SerializeField] private float dif;
[SerializeField] private Heading heading;
// Update is called once per frame
private void Update()
{
// only use the Y component of the objects orientation
// always returns a value between 0 and 360
myHeading = transform.eulerAngles.y;
// also this is always a value between 0 and 360
northHeading = Input.compass.magneticHeading;
dif = myHeading - northHeading;
// wrap the value so it is always between 0 and 360
if (dif < 0) dif += 360f;
if (dif > 45 && dif <= 135)
{
heading = Heading.East;
}
else if (dif > 135 && dif <= 225)
{
heading = Heading.South;
}
else if (dif > 225 && dif <= 315)
{
heading = Heading.West;
}
else
{
heading = Heading.North;
}
}
// Only for debug and demo
// draw a pointer towards north
private void OnDrawGizmos()
{
var northDirection = (Quaternion.Euler(0, northHeading, 0) * Vector3.forward).normalized;
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position, transform.position + northDirection);
var objectDirection = (Quaternion.Euler(0, transform.eulerAngles.y, 0) * Vector3.forward).normalized;
Gizmos.color = Color.blue;
Gizmos.DrawLine(transform.position, transform.position + objectDirection);
}
}
在小演示中,您可以看到物体前进方向的蓝色指针和北方向的红色矢量。您可以看到 Heading 枚举值如何根据对象方向变化。
由于我是在 PC 上完成的,所以我必须手动“调整”北向,稍后您将通过手机获得此信息。