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!

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;
}

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.

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);

Is it possible to do this with only a Vector3 for the origin position? (No Transform)?

Do you know how the relative orientation of one object with respect to another would be determined?