• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
xinfinite33

simple 8 way direction finding algorithm?

10 posts in this topic

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?
0

Share this post


Link to post
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! :D
0

Share this post


Link to post
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.
0

Share this post


Link to post
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 [url="http://en.wikipedia.org/wiki/Atan2"]atan2(y, x)[/url] in most of non-obscure programming languages, which (if given parameters in the expected order) returns an angle [b]in normal mathematical notation[/b] (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 ([b][i]NOT TESTED, use at own risk and test first[/i][/b])
[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.
0

Share this post


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

[code]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);
}
[/code]

:)
2

Share this post


Link to post
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 [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img]

@Á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
0

Share this post


Link to post
Share on other sites
[quote name='xinfinite33' timestamp='1354295734' post='5005740']... 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[/quote]
?__?

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 [url="http://stackoverflow.com/tags/micro-optimization/info"]micro-optimizations[/url] [i]unless[/i] 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 [i]might[/i] perform faster than a version with branching or a vector-and-dot-product approach:
[code]
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));
}
[/code]
[size=1](Though unreadable and perhaps unmaintainable, this was a fun exercise.)[/size]

Though, such optimizations are moot, unless you are calculating millions of [tt]cardinal_directions[/tt] per second...
1

Share this post


Link to post
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 :D. Edited by xinfinite33
0

Share this post


Link to post
Share on other sites
[quote name='xinfinite33' timestamp='1354308376' post='5005837']
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 [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img].
[/quote]

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.
0

Share this post


Link to post
Share on other sites
Remember that in programming, correctness comes first, readability afterwards and speed the last.

Once you write down a slow but correct algorithm in your function, you can always rewrite it for speed later. If you write a speedy one, yet it fails to handle corner cases, it is useless (and you will spend days trying to find the bug). C(++/other low level languages) is very tricky for beginners: they think that because it is advertised for speed, they have to write fast code with it – otherwise, why would they even bother not using Java?

That is a wrong approach. Code is not "slow" in general, only small segments are (copying large arrays, nested loop on one array...). C can, unlike high-level languages, sometimes speed up bottlenecks that cannot be solved by better algorithm. The other 99% of code are performance-wise unremarkable.

When a lumberjack gets a chainsaw instead of saw, he doesn't swing it so he can chop a tree even faster. He would just cut off his leg.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0