- Home /
Relative position
Hi,
let's say I have 2 objects: ObjectA and ObjectB. I want to know what's the position of ObjectB relative to ObjectA. I want the returned position to use the axes of ObjectA (to consider its rotation). I do NOT want ObjectB to be parent of ObjectA. They need to be separated objects.
In other words, the effect I am looking for is the same than parenting the two objects and using ObjectA.transform.localPosition, but I cannot parent these objects.
Is there any magic inside Unity I didn't find yet? Thanks a lot for your time, it's most appreciated!
Is it possible to do this with only a Vector3 for the origin position? (No Transform)?
Answer by Graham-Dunnett · Nov 11, 2012 at 10:22 PM
Isn't this a maths question? AB = posB - posA will give you the vector from A to B. Then get right, up, and forward from the ObjectA's transform. Make sure that these are normalised, then take the dot product of AB with each of these normalised vectors, to get 3 values which are the components of the position of B relative to the axes of A.
Thanks a lot! I can't find how to accept your answer :(
EDIT: Ok, I found the check mark!
Answer by DDP · Nov 12, 2012 at 02:48 AM
Thanks a lot! I'll just post the code I ended up with.
public static Vector3 getRelativePosition(Transform origin, Vector3 position) {
Vector3 distance = position - origin.position;
Vector3 relativePosition = Vector3.zero;
relativePosition.x = Vector3.Dot(distance, origin.right.normalized);
relativePosition.y = Vector3.Dot(distance, origin.up.normalized);
relativePosition.z = Vector3.Dot(distance, origin.forward.normalized);
return relativePosition;
}
Answer by fipsy · Oct 31, 2018 at 01:34 PM
Actually Unity has a built in function for that: Transform.InverseTransformPoint. If you want to get the position of objectB relative to objectA, your code should look like this:
Vector3 relativePosition = objectA.transform.InverseTransformPoint(objectB.transform.position);
actually not, this will get you totally different results than the solution above, which returns exactly the localPosition equivalent, but in the World's coordinates...
Hey, you were totally right. I don't know what I did in my original answer :S but now my example returns the correct position. Thanks for your reply
Your answer
![](https://koobas.hobune.stream/wayback/20220613083718im_/https://answers.unity.com/themes/thub/images/avi.jpg)