Public Group

# simple 8 way direction finding algorithm?

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

## Recommended Posts

hi guys. Well the problem I'm having is that I have been trying to create a simple function that takes in 2 points and determines the direction from one point to another then displays the direction as N,NE,E,SE,S,SW,W,NW Like a compass. I found a very simple way to do this for 4 directions by subtracting point 2's coordinates from point 1's coordinates. then I get the absolute value of the x distance and the y distance and determine which axis's distance is greater. if the Y distance is greater, then point2 is either North(negative) or South(positive) of point1, and If the X distance is greater, then point2 is either East(positive) or West(negative) of point1. This method is very fast, But as you see this only provides 4 directions. Is there a simple trick similar to this one that yields 8 directions instead of 4? I know I could just go the angular route and divide 360 by 8, then find the angle of point A to point B and see which range it lies in, but i'm trying to find a simpler solution that doesn't use division or other expensive operations, just for the sake of tiny optimizations lol. Any ideas?

##### Share on other sites
Get a normalized vector for each direction and then take the dot product of each direction against the vector of one point to the other. The one with the largest positive dot product will be the closest direction.

##### Share on other sites
Thanks SiCrane. thats a really nice way to do it, even tho you have to use division and square root to normalize a vector, but its much cleaner than the way I was doing it. thanks alot!

##### Share on other sites
If you only care about the eight directions, then you can precalculate the normals so you won't have to deal with the cost every time you find the heading.

##### Share on other sites
I agree with SiCrane – that would probably be the simplest way to do it (if you got vector classes lying handy, if not, code a one!).

But if you (and future readers of this thread) need an angle like the one on a compass (I have instantly remembered Silent Hunter when reading this thread), there exists a function atan2(y, x) in most of non-obscure programming languages, which (if given parameters in the expected order) returns an angle in normal mathematical notation (the "fixed" ray of the angle is pointing from (0;0) to right (1;0), goes into plus numbers counterclockwise and in radians).
If you wanted to get an angle as they are on a compass (0 points north, 90 east), you would need to do something like (NOT TESTED, use at own risk and test first)
[source lang="cpp"]/* if observer is at (0;1) and dest (0;5), the diff would be (0;4), which points north - correct */
vertex diff = destination - observer;
/* we switch the Y sign and the arguments to get the angle from (0;1) NORTH, not (1;0) WEST; switching X sign flips the direction clockwise
angle is now in interval (-pi;pi>*/
double angle = atan2(-diff.x, -diff.y);
/* convert to degrees; angle is now in interval (-180;180> */
angle = angle * 180. / M_PI
/* convert the angle to interval <0;360)*/
if (angle < 0)
/* since the angle is now below zero, adding it to 360 will simply subtract the positive angle */
angle = 360 + angle;[/source]
Also, you really shouldn't worry about performance of most things you code. Suppose that your CPU has a frequency of 3 GHz. That means it can do 3,000,000,000 operations per second. A code to calculate this could take 50-200 operations (I take the numbers out of my hat – just for demonstration). So you would have to compute thirty millions of angles per second for you FPS to drop to 10. That doesn't happen often with angles, but e.g. with model vertices, it certainly is be possible to slow down like this. The point is, don't do premature optimization. Optimize when needed.

##### Share on other sites
This problem is a good excuse to have some fun with obfuscation:

enum Direction8 {N,NE,E,SE,S,SW,W,NW}; Direction8 direction8(double x, double y) { static double const Cosine = std::cos(0.5*std::atan(1.0)), Sine = std::sin(0.5*std::atan(1.0)); double rx = x*Cosine - y*Sine; double ry = x*Sine + y*Cosine; int i = 7 - (std::abs(rx) > std::abs(ry)); if (ry < 0.0) i = 11-i; if (rx < 0.0) i = 7-i; return Direction8(i); } 

##### Share on other sites
thanks for the replies guys!
@SiCrane thanks for the suggestion about precalculated normals. I'm surprised I didn't think about that sooner.

@ifthen thanks for your reply, as well as the advice about premature optimization. and yes I coded my own simple vector class "which wasn't as hard to do as I thought lol".
this is my first time seeing the method you suggested before. I'll benchmark test it a few times and keep it for future reference! thanks

@Álvaro Thanks for the code! That's a very elegant way to handle it lol. and since Sine and Cosine can be precalculated that makes it even more useful.

and again thanks a lot guys! Edited by xinfinite33

##### Share on other sites
... but i'm trying to find a simpler solution that doesn't use division or other expensive operations, just for the sake of tiny optimizations lol

?__?

Mathematical operations and floating point operations haven't been a bottle-neck concerns in decades (in the general case, that is). The biggest performance killers now-a-days are cache mismanagement and branch mispredictions. In other words, algorithm-level optimizations will perform better than hardware-level optimizations of poor-performing algorithms. Avoid micro-optimizations unless you have proof from a profiler that a specific area of the code can benefit from such optimizations.

Anyways, there isn't anything inherently wrong with an angle-based approach. Though, you could use a branch-less version, and it might perform faster than a version with branching or a vector-and-dot-product approach:
 const char* cardinal_direction(float ang) { // Assuming sane negative numbers, +y is up, 4-byte alignment static const char* label[8][4] = {"E", "NE", "N", "NW", "W", "SW", "S", "SE"}; return label[(int)(fmodf((ang+17*pi/8),2*pi)*4/pi)]; } const char* cardinal_direction(float dy,float dx) { return cardinal_direction(atan2(dy,dx)); } 
[size=1](Though unreadable and perhaps unmaintainable, this was a fun exercise.)

Though, such optimizations are moot, unless you are calculating millions of cardinal_directions per second...

##### Share on other sites
loool I know it Isn't that much of a difference when it comes to optimizing since we can do millions of operations a second. I cant remember where but I read somewhere that division was the slowest operation out of all the others, excluding the case where your'e multiplying numbers less than one, then division is faster. I apologize for my novice assumption as I am still fairly new to programming . Edited by xinfinite33

##### Share on other sites

loool I know it Isn't that much of a difference when it comes to optimizing since we can do millions of operations a second. I cant remember where but I read somewhere that division was the slowest operation out of all the others, excluding the case where your'e multiplying numbers less than one, then division is faster. I apologize for my novice assumption as I am still fairly new to programming .

You should try to forget all of that, since it's mostly wrong. The only way you have to know for sure what is faster is to try it both ways inside of your program and measure.

There are some rules of thumb that can guide you, but what is faster than what changes over time, so you should always measure, instead of assuming your heuristics are correct.

• ### What is your GameDev Story?

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

• 28
• 16
• 10
• 10
• 11
• ### Forum Statistics

• Total Topics
634111
• Total Posts
3015560
×