w00
w00

Reputation: 26812

Angle, which way to rotate to

For a game i'm trying to calculate the angle between where i'm looking at and the position of another object in the scene. I got the angle by using the following code:

Vec3 out_sub;
Math.Subtract(pEnt->vOrigin, pLocalEnt->vOrigin, out_sub);
float angle = Math.DotProductAcos(out_sub, vec3LookAt);

This code does give me the angle between where im looking at and an object in the scene. But there's a small problem.

When i don't directly look at the object but slightly to the left of it, then it says i have to rotate 10 degrees in order to directly look at the object. Which is perfectly correct.

But, when i look slightly to the right of the object, it also says i have to rotate 10 degrees in order to look directly to the object.

The problem here is, the i have no way to tell which way to rotate to. I only know its 10 degrees. But do i have to rotate to the left or right? That's what i need to find out.

How can i figure that out?

Upvotes: 2

Views: 769

Answers (2)

Nemo
Nemo

Reputation: 71565

I feel the need to elaborate on Ignacio's answer...

In general, your question is not well-founded, since "turn left" and "turn right" only have meaning after you decide which way is "up".

The cross product of two vectors is a vector that tells you which way is "up". That is, A x B is the "up" that you have to use if you want to turn left to get from A to B. (And the magnitude of the cross product tells you how far you have to turn, more or less...)

For 3D vectors, the cross product has a z component of x1 * y2 - y1 * x2. If the vectors themselves are 2D (i.e., have zero z components), then this is the only thing you have to compute to get the cross product; the x and y components of the cross product are zero. So in 2D, if this number is positive, then "up" is the positive z direction and you have to turn left. If this number is negative, then "up" is the negative z direction and you have to turn left while upside-down; i.e., turn right.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799190

You also need to perform the cross product on the vectors. You can then get the direction of the rotate by the direction of the resultant vector.

Upvotes: 1

Related Questions