4

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)

3 Answers 3

14

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.

2

Use the arctangent function. It should be something like this:

double direction(double x, double y) {
    if (x > 0)
        return atan(y/x);
    if (x < 0)
        return atan(y/x)+M_PI;
    if (y > 0)
        return M_PI/2;
    if (y < 0)
        return -M_PI/2;
    return 0; // no direction
}

(Where x and y is the horizontal and vertical speed, M_PI is pi and atan is arctangent function.)

0

In game maker specifically you may use following:

direction = point_direction(x, y, x+x_speed, y+y_speed)
speed = point_distance(x, y, x+x_speed, y+y_speed)

(compare current and future x/y coordinates and return values)

Reverse the process to get x/y_speed:

x_speed = lengthdir_x(speed, direction)
y_speed = lengthdir_y(speed, direction)

Note: Added this post because its still viewed in relation to Game Maker:
Studio and its specific functions. Maybe it has no value for the person who
asked originally but i hope it will help some Game Maker users who wander here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.