Search code examples
mathrotationlanguage-agnosticangle

How would I update an angle, but only within a certain range?


Basically, I have an angle that can only change a certain "turn radius" (say, 60/256 of a rotation) each time it updates. It is changed by an input angle that could be any angle. I need to clamp this input angle so that if it is outside of the turn radius, it will go to the nearest valid angle

For example:

  • Turn radius: 4°
  • Original angle = 0°
  • Input angle = 180.01°
  • Output angle = -4° or 356° (actual output should be within [0, 360) of course)

or

  • Turn radius: 4°
  • Original angle = 0°
  • Input angle = 179.99°
  • Output angle = 4°

or

  • Turn radius: 4°
  • Original angle = 45°
  • Input angle = 46°
  • Output angle = 46°

I am not sure exactly how to properly wrap the angle, so I'm a bit stuck here.


Solution

  • First, find the difference between the original angle and the input angle. (Just subtract.) Then, "normalize" this difference to between -180 degrees and 180 degrees.

    normalized_difference = (((( raw_difference % 360) + 540) % 360) - 180)
    

    Then, if the "normalized" difference is outside the desired range, change it to be within range. Then add the (possibly changed) normalized difference to the original angle to get the output angle. If you wish to normalize the output angle to between 0 degrees and 359.99... degrees, you can do it thus:

    normalized_angle = (((raw_angle % 360) + 360) % 360)