Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move from angle A to B, find shortest direction

Tags:

c#

math

angle

I have an angle A and a target angle B

The range for the angles is -180 to 180

I want angle A to move X degrees towards angle B

The problem I'm facing is if A is say 170 and B is -170, it is clearly faster to increase to 180 and jump to -180, but I always get a negative X when comparing the angles. So instead of taking the fastest way it will take the longest way.

I hope someone will understand my poorly formulated question :)

A = A + ((A-B) / Math.Abs(A-B)) * speed * -1;

Edit: Added code

like image 691
OMGKurtNilsen Avatar asked Dec 12 '25 05:12

OMGKurtNilsen


2 Answers

Calculate the difference between the two angles. If the resulting angle x is bigger than 180 degree, then walk in the other direction using this angle: 360-x.

If you use the range from 0 to 360 you can calculate the difference easier.

like image 145
duedl0r Avatar answered Dec 14 '25 20:12

duedl0r


Here's a complete example:

void Main()
{
    int speed = 5;

    int angleA = 170;
    int angleB = -170;

    int antiClockwiseDistance = Math.Abs(180 - angleA) + Math.Abs(-180 - angleB);
    int clockwiseDistance = angleB - angleA;

    Console.WriteLine(clockwiseDistance);
    Console.WriteLine(antiClockwiseDistance);

    if(clockwiseDistance < antiClockwiseDistance)
    {
        angleA += speed;
    }
    else
    {
        angleA -= speed;
    }

    // TODO: Code to wrap an angle outside the range (i.e. 190 => -170)

    Console.WriteLine(angleA);
}
like image 36
George Duckett Avatar answered Dec 14 '25 18:12

George Duckett