Search code examples
trigonometryangle

Calculating direction angle from x and y speed


I'm developing game in Game Maker kind of program (not actual Game Maker, though), because I've failed in coding games in real languages (can code normal apps, just not games) so many times.

Anyway, in program that I'm using direction function was proven to be buggy at times. However x and y speed of object are always correct, so I'd like to calculate direction angle (in degrees) from those. Unfortunately I'm not math genius and I'm always failing at trigonometry ;(. Can you help me?

My game making IDE's angle coordinate system is as follows:

         270 deg.
  180 deg.      0 deg.
         90 deg.

Positioning system is like in most environments (0,0 in top-left)


Solution

  • Math libraries usually come with a function called atan2 just for this purpose:

    double angle = atan2(y, x);
    

    The angle is measured in radians; multiply by 180/PI to convert to degrees. The range of the angle is from -pi to pi. The 0-angle is the positive x-axis and the angle grows clockwise. Minor changes are needed if you want some other configuration, like the 0-angle being the negative y-axis and the range going from 0 to 359.99 degrees.

    The main reason to use atan2 instead of atan or any of the other inverse trig functions is because it determines the correct quadrant of the angle for you, and you don't need to do it yourself with a series of if-statements.