Jump to content
  • Advertisement
Sign in to follow this  
leilock

Finding the closest radian angle

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!