Local Space and World Space in Unity
Something important to note when working with Unity’s Transform component is the difference between ‘local space’ and ‘world space’. Essentially, if we’re moving an object according to its position in world space, we’re moving it in relation to the ‘origin’ of the world (point 0, 0, 0). This will be the same for all objects in the scene, so if I position two cubes at point 0, 1, 0 in world space they’re guaranteed to overlap.
Something you might have noticed is what happens to the values in a Transform component when we parent one object to another:
The cube isn’t moving as a result of this — its Transform is just changing over to local space, which in this case means in relation to the parent object. So we can now see far on the X, Y, and Z axes Cube 3 is from Cube 2 rather than from the world’s origin. If I was to zero these axes out for Cube 3, the object wouldn’t necessarily be at point 0, 0, 0 according to world space (unless of course the parent object was positioned there).
This is an important distinction to bear in mind, particularly when it comes to changing the position or rotation of an object that is parented to another object. In a lot of those cases, we’re going to want to change its Transform.localPosition or Transform.localRotation respectively, as opposed to its Transform.position or Transform.rotation.
As a quick example of this, lets imagine Cube_3 is parented to Cube_2. Cube_2 is moving forward constantly, and since Cube_3 is a child object it’ll naturally follow along with it. If we then wanted Cube_3 to, say, bob up and down while still following Cube_2, we’d need to make sure we’re changing Cube_3’s localPosition to ensure we’re not in fact forcing it back to a specific position in world space (defying/ignoring Cube_2’s ever-changing position).
For debugging purposes, if you find changing an object’s position or rotation isn’t quite working out, it might be worth swapping over to its local equivalents to see if that addresses the problem.
Lastly, there are in fact a number of Transform methods that can convert a world space position or vector to local space and vice versa. These are mentioned in Unity’s documentation for the Transform class, but I’ll also include them here along with their descriptions 😉
World Space to Local Space
- InverseTransformDirection — Transforms a direction from world space to local space.
- InverseTransformPoint — Transforms position from world space to local space.
- InverseTransformVector — Transforms a vector from world space to local space.
Local Space to World Space
- TransformDirection — Transforms direction from local space to world space.
- TransformPoint — Transforms position from local space to world space.
- TransformVector — Transforms vector from local space to world space.