In this lesson, you will learn how to accurately calculate the position of an object relative to different coordinate systems using Unity’s transformation logic.
Why Coordinate Spaces Matter
Imagine you are building a game where a player holds a sword. The sword’s position is stored relative to the player's hand (Local Space). However, the physics engine needs to know where that sword is in the entire game world (World Space) to detect collisions. If you don't convert these coordinates, your sword might appear to be floating miles away from the player.
The Transformation Matrix
At the heart of this process is the 4x4 Transformation Matrix. This mathematical grid holds all the data needed to translate, rotate, and scale an object. When you move an object in the Unity Inspector, you are essentially updating its matrix. To convert a point from one space to another, we multiply that point’s coordinates by the relevant matrix.
Converting Between Spaces
In your scripts, you don't need to do the complex matrix math by hand, but you must understand the two directions of movement:
- Local to World: You have a position relative to a parent (like a child object's coordinates) and want to know its exact spot in the scene.
- World to Local: You have a world coordinate (like a mouse click position) and want to know where that point falls relative to a specific object.
Here is how you apply these transformations in code:
// Converting a local point to world space
Vector3 worldPosition = transform.TransformPoint(localPosition);
// Converting a world point to local space
Vector3 localPosition = transform.InverseTransformPoint(worldPosition);
By using TransformPoint, you translate a point based on the object's current position, rotation, and scale. Conversely, InverseTransformPoint strips away the object's current transformations to tell you where that coordinate "lives" in the object's internal space. This is essential for features like local-space movement, object interaction, or procedural effects where you need to sync positions across different parent-child hierarchies.
Key Takeaway: Use TransformPoint to map coordinates into the world, and InverseTransformPoint to map them into an object's local perspective.