Move from angle A to B, find shortest direction
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 wil开发者_运维技巧l 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
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.
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);
}
精彩评论