Описание
Возвращает нормализованный вектор, представляющий синюю ось преобразования в мировом пространстве.
В приведенном ниже примере показано, как управлять положением GameObject по оси Z (синяя ось) преобразования в мировом пространстве. В отличие от Vector3.forward, Transform.forward перемещает GameObject с учетом его поворота.
Когда игровой объект вращается, синяя стрелка, обозначающая ось Z игрового объекта, также меняет направление. Transform.forward перемещает GameObject по оси синей стрелки (Z).
Информацию о перемещении GameObject по оси 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;
// Вычисляет угол между целевым преобразованием и этим объектом
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);
}
}