Search code examples
objective-cmathangledegrees

Figuring out direction of degrees


I'm probably overthinking this, but, say you have the following variables;

  • Starting degrees
  • Ending degrees
  • Incremented degrees (i.e. starting degrees + X)

How can you figure out the direction of the degrees? I.e, 0->359 being clockwise and 359->0 being counterclockwise.

Here's a couple of examples:

Starting at: 357 degrees
Ending at: 337 degrees
Incremented by: 20
Direction: Counterclockwise

Starting at: 10 degrees
Ending at: 350 degrees
Incremented by: 20
Direction: Counterclockwise

Starting at: 357 degrees
Ending at: 17 degrees
Incremented by: 20
Direction: Clockwise

How would you figure out the direction as safely as possible? One quick dirty solution would be to use module, but, what happens if the incremented number is off by 1-2 degrees?

The ideal solution would be a way to detect whichever direction is closest to the incremented number. In case that doesn't make sense, here's an example:

Starting at: 17 degrees
Ending at: ~347-357 degrees
Incremented by: ~20-30
Direction: Counterclockwise

It wouldn't be clockwise because that difference is approximately ~330-340.

Let me know if it doesn't make sense and I'll try my best to reword it.


Solution

  • Calculate two variants for CW and CCW

    E1 = (Start + Increment) %% 360
    E2 = (Start + 360 - Increment) %% 360
    

    and check what variant gives smaller absolute difference with ending angle.

    S:0; E:20; 
    
    if I=20
    CW: 0+20=20
    CCW: 0 + 360-20=340
    E is closer to CW result
    
    if I=340
    CW: 0+340=340
    CCW: 0 + 360 - 340 = 20
    E is closer to CCW result