Fast way to compare angles.
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
wouldn't
be even faster and do the exact same thing?
if( A dot B < (A.length * B.length * cosx))
be even faster and do the exact same thing?
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
-Cuppo
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.
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).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement