It is easy to get the angle between two vectors using Vector3.Angle, but this only gives an absolute value for the angle. How do you tell if one direction is to the left or to the right of the other?
It seems as though it should be easy, but in fact it’s a little bit subtle. I’ve attached a function (in both JS and C# versions) that illustrates how to go about it. You need to supply a forward direction, the direction that you want to check for left/right of forward and an up direction. The functions return -1 when the target direction is left, +1 when it is right and 0 if the direction is straight ahead or behind.
As is so often the case, the magic ingredient in the function is the cross product.
many many thanxxx
… how long was i searching for this solution…
Now my Direction Display works !!!
I really miss this in the Doc’s !!!
Great Community !!! kerstin
//returns -1 when to the left, 1 to the right, and 0 for forward/backward
public static function AngleDir(fwd: Vector3, targetDir: Vector3, up: Vector3) : float {
var perp: Vector3 = Vector3.Cross(fwd, targetDir);
var dir: float = Vector3.Dot(perp, up);
if (dir > 0.0) {
return 1.0;
} else if (dir < 0.0) {
return -1.0;
} else {
return 0.0;
}
}
public static float AngleDir(Vector2 A, Vector2 B)
{
return -A.x * B.y + A.y * B.x;
}
This returns a negative number if B is left of A, positive if right of A, or 0 if they are perfectly aligned.
It works by rotating B 90 degrees counter-clockwise (which is simply {-B.y, B.x}) and then taking the dot product to see if the rotated vector is ahead or behind A. (Make some vector combinations with your fingers and wiggle them around until you convince yourself this works! ;))
if all you need to know is what side an object is on there is another way.
Vector3 localPos = objectFacing.InverseTransformPoint(objectToTest.transform.position);
if (localPos.x < 0.0f) // left side
else if (localPos.x > 0.0f) // right side
else // center