Keep angle between 1 and 180 degrees

268 views Asked by At

I have the following which returns the rotation in degrees of an object, lensParentRight, through 360.

This is in Adobe Animate HTML5 Canvas (create.js/easel.js would apply). cylinderAngle is just an offset.

var cylinderAngleText = Math.abs((Math.round(((root.lensParentRight.rotation + cylinderAngle) * 100) / 100))) + "\u00B0"; 

I want to keep the angle returned between 1 and 180.

How would this be done in JavaScript?

2

There are 2 answers

0
Mark George On BEST ANSWER

You could always limit your variable values using mod "%" at end of your mathematical expression. ((exp)%180) in your case. I hope that helps.

0
Nicholas Carey On

To add 2 numbers and constrain the value to lie within a specified range requires that you implement overflow on the results of the addition. Something like this:

function add_and_constrain_to_range( a, b, lo, hi ) {
  const range = hi - lo ;
  const sum   = a  + b  ;
  const result = lo + ( sum % range ) ;
  return result;
}