# Finding the closest radian angle

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

## Recommended Posts

I've got some sprites that when they collide, i need them to snap to the closest of six directions. Given a radian angle of a point relative to an origin, how do i find which of the 6 directions is the closest? At this point i have an algorithm that's close, but it gitches out sometimes so the math has to be wrong. Also, if anyone knows of smarter ways to do this i'm open to suggestions. Thanks!

##### Share on other sites
The easiest way would be to compare the red vector to each of the 6 static vectors by using the dot product operation.

The highest dot product indicates the closest match, where a dot product of -1 would indicate that the vectors are pointing directly away from each other.

##### Share on other sites
If you don't already have the angle, then you can use atan2 on the vector to get it. If C++ isn't your language, then you can get away with using tan with some quadrant logic.

Imagine that each direction has a angular region of size PI/3 around it, and each region is centered at the direction. All you need is a translation and a scale in order to determine which region the angle is in. The translation centers the region, which the translation changes the size of the range from 2PI to 6. If I did my math correctly, the formula should be:

direction = (int)((angle + PI/6) / (PI/3));

The direction will either be from 0 to 5 for all positive radians, or from -2 to 3 if you're using both positive and negative radians (as it appears from your diagram).

##### Share on other sites
Thanks guys! Should be good now.

1. 1
2. 2
3. 3
Rutin
20
4. 4
5. 5
khawk
14

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633655
• Total Posts
3013179
×