Question

My game units have an angle variable, and a targetAngle variable. These variables range from 1 to 360 degrees.

The angle variable should always move towards the targetAngle variable.

The problem is, it doesn't happen in the shortest way. When the targetAngle is 350 degrees, and the current angle is only 10 degrees, the variable should only move by 20 degrees instead of incrementing by 340 degrees, as I have now.

How can I make the angle variable move towards the targetAngle variable in the shortest way?

Live demo: http://jsfiddle.net/zNsbc/

var angle = 10;
var targetAngle = 350;

setInterval(function() {

    if ( angle > targetAngle ) {
        angle--;
    }
    else if ( angle < targetAngle ) {
        angle++;
    }    

    $("#angle").text(angle);

}, 10);
Was it helpful?

Solution

You should realize that 360 is the same as 0, so you can compare angle with targetAngle and also with targetAngle+360 and move it to the direction to which it is closest (consider -360 as well for angles close to 0 and targetAngle close to 360)

So your example:

angle:            10
targetAngle:      350 (diff 340)
targetAngle+360:  710 (diff 700)
targetAngle-360: - 10 (diff  20)

angle is closest to targetAngle-360, so you would decrement it, instead of incrementing it

Note: make sure to take absolute value for the difference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top