Angle between 3d vectors

Started by
3 comments, last by Zakwayda 15 years, 8 months ago
This is what I have

v1.Normalize();
v2.Normalize();
angle=acos(v1.Dot(v2));
std::cout<<"angle:"<<angle<<std::endl;
if (angle>M_PI)
	return true;

The trouble is acos returns between 0 and PI so my check is never true; so how do I get the angle between 0 and 2pi ?
Advertisement
The answer is simple: you can't. The angle between two vectors can never be larger than 180°.
Quote:Original post by aarbron
This is what I have

*** Source Snippet Removed ***

The trouble is acos returns between 0 and PI so my check is never true; so how do I get the angle between 0 and 2pi ?
Without a frame of reference, you can only compute the unsigned angle between two vectors in 3-d.

Here is a function that computes the signed angle between two 3-d vectors, using a third vector as a reference to determine the sign:
float signed_angle(const vec3& v1, const vec3& v2, const vec3& reference){    vec3 c = cross(v1, v2);    float angle = std::atan2(length(c), dot(v1, v2));    return dot(c, reference) < 0.f ? -angle : angle;}
Post back if you have any questions about how (or why) it works.
Thanks, here's how it looks now
v1.Normalize();v2.Normalize();Vec3 c=v1.CrossProduct(v2);angle=std::atan2(c.Magnitude(),v1.Dot(v2));angle=c.Dot(Vec3(1.f,0.f,0.f)) < 0.f ? -angle : angle;std::cout<<"angle:"<<angle<<std::endl;if (angle>M_PI_2+0.0001f||angle<-M_PI_2-0.0001f)	return true;

I suppose the actual value of the ref vector doesn't really matter ?
Quote:I suppose the actual value of the ref vector doesn't really matter ?
Well, it only matters if it matters, if you get my meaning :)

In other words, whether or not it matters depends on the context, so that's really up to you to determine. I will say though that this problem often comes up in the context of solving an essentially 2-d AI problem in a 3-d environment, in which case you can just compute the signed angle between two 2-d vectors, like this:
float angle = atan2(perp_dot(v1,v2), dot(v1,v2));
Note that for both the 2-d and 3-d versions of this algorithm, you don't need to normalize the vectors prior to finding the angle. Also, atan2() returns an angle in the range [-pi, pi] (in case it matters for what you're using it for).

This topic is closed to new replies.

Advertisement