# Equivalent of GameMakers's function angle_difference

Attention Topic was automatically imported from the old Question2Answer platform.

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.

Is there in godot a function 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.

static func angle_to_angle(from, to):
return fposmod(to-from + PI, PI*2) - PI

How to convert angle form transform.rotation to vector?

Also i find math explanation behind GameMaker’s function GMLscripts.com :: angle_difference

Huder | 2018-04-22 20:22

In Godot 3, it is polar2cartesian(radius, angle)

@GDScript — Godot Engine (3.0) documentation in English

Prior to that,

var normal = Vector2(sin(angle), cos(angle))

avencherus | 2018-04-23 10:33