Topic was automatically imported from the old Question2Answer platform.

Asked By

Huder

In GameMaker: Studio there is a function angle_difference(angle1, angle2)
This returns new angle value between -180 and 180 degree. I need something like that.

There’s not a lot of built-in support for operations on degrees (Vector math is the generally supported way of doing these kinds of things).

This function should do the trick:

# returns the difference (in degrees) between angle1 and angle 2
# the given angles must be in the range [0, 360)
# the returned value is in the range (-180, 180]
def angle_difference(angle1, angle2):
var diff = angle2 - angle1
return diff if abs(diff) < 180 else diff + (360 * -sign(diff))

There is an angle_to method available in Vector2, but you’d have to convert your angles to vectors.

For my purposes I wrote a small library function for my projects, since it comes up often enough. This preserves the sign information so it will rotate to the nearest and stay within the -180 to 180 range.