Objects position relative to another objects rotation
I'm working on a function that will figure out one characters position relative to another. For instance, if a character is facing to 90 degrees, I want to detect if another character is along a line to, say, 70 degrees from the origin (the first character). Would there be a way to do this easily? I know that Vector3.Angle exists, but I don't know how to use it, let alone use it to do this if it even could. Thanks!
Answer by Eno-Khaon · Jan 23, 2016 at 08:13 AM
Well, let's start from the top.
Knowing the positions of Character 1 (char1) and Character 2 (char2), the position of either relative to each other is:
// C#
Vector3 char1ToChar2 = char2.transform.position - char1.transform.position;
Vector3 char2ToChar1 = char1.transform.position - char2.transform.position;
Knowing these vectors, they can be normalized as necessary to make the process simpler down the road.
char1ToChar2 = char1ToChar2.normalized;
With these directions in mind, you then look at the direction the character(s) is facing. From there, the angle can easily-enough be determined.
Vector3 relativeAngle = Vector3.Angle(char1.transform.forward, char1ToChar2);
With this out of the way, you can easily make use of the angle difference for any purpose you need.
Edit: Additionally, you can easily transform the orientation from a world vector to a local one by using InverseTransformDirection.
Vector3 localRelativePosition = char1.transform.InverseTransformDirection(char1ToChar2);