# Using angle_difference to calculate shortest turn to target [Gamemaker]

I've tried, but I cannot understand angle_difference.

I have an object, oTurretDetTurret, which turns to face its Target, which lies at the angle DirectionOfTarget from it.

It does this by updating its direction thus:

direction = direction + SpinDirection

SpinDirection can be either +3 or -3, meaning it can turn in either direction at a rate of 3 degrees per step.

What determines the direction it turns in is the angle between its current direction and the DirectionToTarget. I want the turret to turn in the direction with the shortest number of degrees to travel.

I've been using this:

if angle_difference(direction, DirectionToTarget) > 0 {
direction = direction + 3
} else if angle_difference(direction, DirectionToTarget <= 0 {
direction = direction - 3
}


However, in game this just means that the turret faces the opposite direction to its target at all times, oscillating back and forth slightly.

In my understanding, angle_difference returns the smaller of the two angles between two directions.

For example, if the turret's direction is 300 degrees and the DirectionToTarget is 90 degrees, angle_difference should return +150, the smaller of the two angles, and thus my above code should move the turret counter-clockwise towards 90 degrees.

Can anybody help me?

• Thank you very much! I'm so used to using <- in Gamemaker to cover the boundary number itself, not just less or greater than it, that I didn't consider that angle_difference would not return 0. The other issue in my code is that I had the +3 and -3 in the wrong order, as illuminated by your answer. So now if angle_difference > 0 , the direction changes by -3 (moving clockwise) and if < 0 it changes by +3 (anti-clockwise). Thank you for the explanation! – Bonfire Dog Jul 9 '16 at 7:52
• Thank you for taking the time to answer: I did think that my DirectionToTarget was off by 180 as you say, but in the end it turned out to be because I included 0 in the angle_difference calculation, which it seems not to count. As for the increment, I tested it with +1 and -1` and it didn't seem to make a difference, and the code now works with any increment I choose. – Bonfire Dog Jul 9 '16 at 7:53