返回一个标准化的向量,表示变换在世界空间中的蓝色轴。
以下示例展示了如何操作游戏对象的 Z 轴(蓝色轴)在世界空间中的位置。与 Vector3.forward 不同,Transform.forward 移动游戏对象时也考虑了其旋转。
当游戏对象旋转时,表示游戏对象 Z 轴的蓝色箭头也会改变方向。 Transform.forward 在蓝色箭头轴 (Z) 上移动游戏对象。
要忽略旋转,在 Z 轴上移动游戏对象,请参见 Vector3.forward.
using UnityEngine;
public class Example : MonoBehaviour { Rigidbody m_Rigidbody; float m_Speed;
void Start() { //Fetch the Rigidbody component you attach from your GameObject m_Rigidbody = GetComponent<Rigidbody>(); //Set the speed of the GameObject m_Speed = 10.0f; }
void Update() { if (Input.GetKey(KeyCode.UpArrow)) { //Move the Rigidbody forwards constantly at speed you define (the blue arrow axis in Scene view) m_Rigidbody.velocity = transform.forward * m_Speed; }
if (Input.GetKey(KeyCode.DownArrow)) { //Move the Rigidbody backwards constantly at the speed you define (the blue arrow axis in Scene view) m_Rigidbody.velocity = -transform.forward * m_Speed; }
if (Input.GetKey(KeyCode.RightArrow)) { //Rotate the sprite about the Y axis in the positive direction transform.Rotate(new Vector3(0, 1, 0) * Time.deltaTime * m_Speed, Space.World); }
if (Input.GetKey(KeyCode.LeftArrow)) { //Rotate the sprite about the Y axis in the negative direction transform.Rotate(new Vector3(0, -1, 0) * Time.deltaTime * m_Speed, Space.World); } } }
另一个示例
using UnityEngine;
// Computes the angle between the target transform and this object
public class Example : MonoBehaviour { public float angleBetween = 0.0f; public Transform target;
void Update() { Vector3 targetDir = target.position - transform.position; angleBetween = Vector3.Angle(transform.forward, targetDir); } }