Question

I have two angles: from, to and clockwise direction. And defined angle. Angles are between 0 and 360 deg. I need a function that returns is defined angle is between from and to angles.
For example:

function isInRange(from, to, angle){
    ...
}  
isInRange(30, 330, 90);  // true
isInRange(30, 330, 0);  // false
isInRange(330, 30, 90);  // false
isInRange(330, 30, 0);  // true

Help please)

Was it helpful?

Solution 2

First make sure that the angles are comparable, then it's a simple range comparison:

function isInRange(from, to, angle){
  // make sure to >= from
  while (to < from) to += 360;
  // make sure angle >= from
  while (angle < from) angle += 360;
  // compare
  return angle >= from && angle <= to;
}

OTHER TIPS

function isInRange(from, to, angle){
   from = from % 360;
   to= to % 360;

if(from > to){
return((angle > from) || ( angle < to))
} else if ( to > from){
return((angle < to) && ( angle > from))
} else{ // to == from 
 return (angle == to)
} 

}

You also need to think what you want to do when from % 360 === to % 360, for example

function isInRange(from, to, angle) {
    var _from  = from  % 360,
        _to    = to    % 360,
        _angle = angle % 360;
    if (_from  < 0) _from  += 360; // (-500) % 360 === -140 :(
    if (_to    < 0) _to    += 360;
    if (_angle < 0) _angle += 360;
    if (_from === _to) {
        if (to > from)
            return true; // whole circle
        return _angle === _from; // exact only
    }
    if (_to < _from)
        return _angle <= _to || from <= _angle; // _angle outside range
    return _from <= _angle && _angle <= _to;    // _angle inside range
}
// whole circle examples
isInRange(   0,  360,  180); // true
isInRange(   0,    0,  180); // false
isInRange(  90,   90,   90); // true
// negative examples
isInRange(  -1,    1,    0); // true
isInRange(   1,   -1,    0); // false
isInRange(-180,   -1,  270); // true
// weird examples
isInRange(1085, -180, -270); // true, same as (5, 180, 90)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top