Easy way to keeping angles between -179 and 180 degrees

后端 未结 16 2667
长发绾君心
长发绾君心 2020-12-04 16:41

Is there an easy way to convert an angle (in degrees) to be between -179 and 180? I\'m sure I could use mod (%) and some if statements, but it gets ugly:


/         


        
16条回答
  •  眼角桃花
    2020-12-04 17:22

    Not that smart, too, but no if.

    angle = (angle + 179) % 360 - 179;

    But I am not sure how Java handles modulo for negative numbers. This works only if -1 modulo 360 equals 359.

    UPDATE

    Just checked the docs and a % b yields a value between -(|b| - 1) and +(|b| - 1) hence the code is broken. To account for negative values returned by the modulo operator one has to use the following.

    angle = ((angle + 179) % 360 + 360) % 360 - 179;
    

    But ... no ... never ... Use something similar to your initial solution, but fixed for values smaller then -179.

提交回复
热议问题