In this lesson, you will learn how to make an object move forward based on its own rotation rather than the static "World North" direction.
Why Global Movement Falls Short
When you move an object using transform.position += Vector3.forward * speed, Unity moves it along the world's Z-axis. If your character turns to face a different way, they will still slide toward the same world direction. To create intuitive player controls, you need movement that understands which way the character is currently facing.
Using TransformDirection
Unity provides the TransformDirection method to convert a direction from "local space" (the object's perspective) to "world space" (the scene's perspective). Think of this like asking a person to "walk forward"—they don't need a map; they just need to know which way their nose is pointing.
By passing a local direction into TransformDirection, Unity calculates exactly which world vector that direction maps to based on the object's current rotation.
Practical Implementation
Here is how you apply this to a simple movement script:
void Update()
{
// Define the movement in local space (e.g., Forward)
Vector3 localMovement = Vector3.forward;
// Convert local "forward" to world-space based on this object's rotation
Vector3 worldMovement = transform.TransformDirection(localMovement);
// Apply the movement to the position
transform.position += worldMovement * Time.deltaTime * speed;
}
In this example, if your character is rotated 90 degrees to the right, transform.TransformDirection(Vector3.forward) will automatically return the world's Right axis. If you rotate the character 180 degrees, it will return the world's Back axis. This allows your character to consistently "walk forward" regardless of how they are turned in the scene.
This approach is the foundation for most third-person controllers. By using the transform’s orientation to define the vector, you ensure that the input provided by the player always results in movement that makes sense relative to what they see on screen.
Key Takeaway: Use transform.TransformDirection to convert local movement vectors into world space, allowing your objects to move naturally in the direction they are currently facing.