Public Group

# Angle between 3d vectors

This topic is 3824 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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 ?

##### Share on other sites
The answer is simple: you can't. The angle between two vectors can never be larger than 180°.

##### Share on other sites
Quote:
 Original post by aarbronThis 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.

##### Share on other sites
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 ?

##### Share on other sites
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).

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 9
• 9
• 9
• 34
• 16
• ### Forum Statistics

• Total Topics
634123
• Total Posts
3015654
×