What space is this coordinate in? All GameObjects in Unity must have a Transform component to define its position, rotation, and scale in the default space which is typically world space. Every Transform has their own relative local space that provides the ability for GameObjects to be parented thereby changing the Transform to be based on the local parent rather than world. This is known as a frame of reference as the point of view is off the transform. Therefore, a child GameObject stays the same in local space but not in world space. It essentially just means working in a different coordinate system.
The following space transformations can be abstracted away by using matrices which will be discussed in another post.
World Space to Local Space
In order to go from world to local, the world point must be made relative to the origin of the local space. this can be done by subtracting vectors to get the vector from origin to the world point. After finding this vector, the dot product can be used to align the vector if it has been rotated by projecting onto the basis vectors of the local space coordinate system.
Basis vectors refer to the vectors of the coordinate system in world space, which in the case of 2D vectors would be right and up, and are usually unit (normalized) vectors.
Vector2 WorldToLocal(Vector2 worldPoint) {
Vector2 relativePoint = worldPoint - transform.position;
float x = Vector2.Dot(relativePoint, transform.right);
float y = Vector2.Dot(relativePoint, transform.up);
return new Vector2(x, y);
}
Local Space to World
To go from local space to world, scale the basis vectors of the transform by multiplying with the local point and adding. This gets us the offset from the transform in world space. The last step is to then add the position of the transform to this offset to get the world space coordinates.
Vector2 LocalToWorld(Vector2 localPoint) {
Vector2 offset = (transform.right * localPoint.x) + (transform.up * localPoint.y);
// position is a Vector3 so a cast is needed for this example
return (Vector2)transform.position + offset;
}