# Nearest angle between vectors

I have a spaceship. Green vector is an origin (direction spaceship points to). Red vectors are direction where velocity will be applied.

I need to rotate spaceship with blue angle (nearest). In pseudocode I have:

angle = Vector2.Angle(velocity, origin)
spaceship.rotation += angle


But in this case (with angle addition) it will rotate only counterclockwise. In first two cases (pictures) this is wrong, there should be angle distraction. The third case is ok, it will get the right velocity in nearest angle.

So, what is the condition when I should use distraction instead of addition angle?

• You just need to allow angle to be negative. Then you can always use addition. – Marconius Oct 16 '15 at 23:45

I'll assume that you're coding in Unity. We can detect orientation by checking the sign of a cross product:

 float angle = Vector2.Angle(velocity, origin);
Vector3 cross = Vector3.Cross(velocity, origin);

if (cross.z > 0)
angle = 360 - angle;

• You are right, it's Unity. Thanks for the answer. I forgot about cross product. It works. – Max Frai Oct 16 '15 at 23:54

I'm assuming that you are in a 2d world. You could calculate the cross-product of the green and red vectors and check the sign of the z-axis.

Let $G = (a, b)$ be the green vector and $R = (c, d)$ be the red vector.

Extend them to the $\mathbb{R}^3$ and calculate the cross-product. So:

$$\begin{vmatrix} i & j & k \\ a & b & 0 \\ c & d & 0 \end{vmatrix} = (ad - bc) k$$

If $ad - bc \gt 0$, then the green vector is on the right, just like your first and second image.

If $ad - bc \lt 0$, then the green vector is on the left, just like your third image.