Finding relative position of 1 object relative to another using the second's coordinate system.

I’m having trouble looking up the answers for this problem I have because Im not sure what its called exactly. I know we get the relative position of a child to a parent with the child’s local position. How do I find the relative position of an object and the parents of its parent? Or another game object unattached entirely?

Thanks in advance.

Transform obj1;
Transform obj2;
obj2.InverseTransformPoint(obj1.position);
7 Likes

To get the relative position of an object to its parent’s parent, or to any other game object, you can use the Transform.InverseTransformPoint method. This method takes a world space position as input, and returns the relative position of that point to the transform’s local space.

Here’s an example of how you could use the Transform.InverseTransformPoint method to get the relative position of an object to its parent’s parent:

GameObject childObject;
GameObject grandparentObject;

Vector3 childLocalPosition = grandparentObject.transform.InverseTransformPoint(childObject.transform.position);

In this example, the childLocalPosition variable will contain the relative position of the childObject to the grandparentObject.

You can also use the Transform.InverseTransformPoint method to get the relative position of an object to any other game object, as long as you have a reference to the transform of the target game object.

Here’s an example of how you could use the Transform.InverseTransformPoint method to get the relative position of an object to another game object:

GameObject objectA;
GameObject objectB;

Vector3 objectALocalPosition = objectB.transform.InverseTransformPoint(objectA.transform.position);

In this example, the objectALocalPosition variable will contain the relative position of the objectA to the objectB.

I hope this helps! Let me know if you have any other questions.

2 Likes

Ah cool. Thank you both!