# Relative angles with dot product (2D)

## Recommended Posts

ViniGodoy    100
Hi.

I recently found a dot product relative angle calculation for unit vectors as follows:

[font="courier"][code]float Vector2D::angleBetween(const Vector2D& other) const
{
float dp = dot(other);

if(dp >= 1.0) dp = 1.0f;
else if(dp <=-1.0) dp = -1.0f;

float angPi = (float)acos(dp);

//side test
return y*other.x > x*other.y ? -angPi : angPi;
}[/code][/font]

But i could not figure out where this "side test" came from.
Does it work? And how?

I usually use the traditional atan2 - atan2 calculation, but if this solution is really correct I could use in machines where this atan2 is not implemented.

##### Share on other sites
ViniGodoy    100
Sorry, just now I realised that this is a disguised test of the perp dot product signal.

##### Share on other sites
Dirk Gregorius    2757
You could simply do this:

angle = atan2( abs( cross( v2, v1 ), dot( v2, v1 ) );

##### Share on other sites
alvaro    21263
[quote name='Dirk Gregorius' timestamp='1312574437' post='4845187']
You could simply do this:

angle = atan2( abs( cross( v2, v1 ), dot( v2, v1 ) );
[/quote]

Man, you should read the question before giving out some canned answer.

##### Share on other sites
Emergent    982
Also, just FYI, that" canned answer" is a bit wrong. Although the norm of the cross product gives you the magnitude of the sine of the angle, it doesn't give the sign, which is really what matters. Without that, you have no more information than the cosine gives you. You need the full determinant, sign included. I liked Vini's description as "perp dot product."

## Create an account

Register a new account