# Fast way to compare angles.

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

## Recommended Posts

Hey I just realized this today and thought I'd share this trick. If you have a vector A, and you want to see if another vector B is within x degrees of it you can use this trick. Instead of going: float angle1 = arctan A float angle2 = arctan B if( |angle1-angle2| < x) //bla bla You can go: A.normalize B.normalize if( A dot B < cos x) //bla bla Caching the cosine makes the entire operation about twenty times faster. I haven't tried caching the squareroot yet. Without caching, the operation below is still 4 times faster. -Cuppo

##### Share on other sites
wouldn't
if( A dot B < (A.length * B.length * cosx))

be even faster and do the exact same thing?

##### Share on other sites
Yea that's the basic idea, except for most of the time you don't know the length of the vector which is why I had the two normalize statements.
-Cuppo

##### Share on other sites
Well since normalization is v / v.length the length ought to either be known or easily computed basicly my method saves you the divisions / multiplications that normalization would give per element.

##### Share on other sites
You might be able to skip the square root completely if you square both sides. Of course this introduces the problem that angles that are opposite (cos = -1) will look like right on top of each other, since the sign of the dot product would be lost. Anyway, depending on the situation you might be able to rule out that possibility, or check for the sign of the product (as long as cos x > 0).

##### Share on other sites
That's nice. I didn't think of that.
So once the cosine is cached, this operation will be blazing.
Thx for that tip avaro.
-Cuppo.

• ### What is your GameDev Story?

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

• 15
• 14
• 46
• 22
• 27
• ### Forum Statistics

• Total Topics
634047
• Total Posts
3015232
×