Math – How to Deal with Angle Wraparounds

math

Angle A is a degree angle that keeps increasing by increments and Angle B is the stopping point of Angle A (think 'Spin-the-bottle' where Angle A is the current angle of the bottle Angle B is the angle needed to point to your crush and the bottle spins at a fixed rate clock-wise).

To do this, I've been trying to compare Angle A and Angle B with inequalities. If Angle A is 60 degrees and Angle B is 80 degrees, this is no problem. If Angle A is 350 degrees and Angle B is 10 degrees however, the inequality thinks that Angle A has crossed Angle B even though it hasn't.

How do I compare angles when they wraparound at 360 degrees?

This is some pseudo-code for what I have so far:

int AngleB = 30;
int AngleA = 300;

void Update() {
    AngleA += 13;
    if (AngleA > AngleB) {
        AngleA = AngleB;
    }
}

Update: Here's my new method that wraps Angle A relative to Angle B:

double GetAngleDifference(double from, double to)
{
    double difference = to - from;
    while (difference < -180) double += 360;
    while (difference > 180) double-= 360;
    return difference;
}

Best Answer

Any angle is equivalent to the angle + 360 degrees.

So if you are increasing a, but a > b (numerically), then add 360 to b at the start. Now a < b works for your loop.

e.g.

a = 270
b = 45
b += 360 // = 405
while (a < b)
  a += ... // 270 up to 405

If you are decreasing a but b > a (numerically), then add 360 to a at the start. Now a > b works for your loop.

e.g.

a = 10
b = 310
a += 360 // = 370
while (a > b)
  a -= ...  // 370 down to 310

That's not the full pseudocode, but illustrates the two cases where you need to worry about "crossing" the 360 mark.

Related Topic