检查角度是否在顺时针方向的“from”和“to”之间

时间:2014-03-26 11:02:28

标签: javascript math geometry trigonometry angle

我有两个角度:fromto和顺时针方向。并定义角度。角度在0到360度之间。我需要一个函数返回定义的角度介于fromto之间 例如:

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

请帮助)

3 个答案:

答案 0 :(得分:4)

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)
} 

}

答案 1 :(得分:2)

首先确保角度具有可比性,然后进行简单的范围比较:

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;
}

答案 2 :(得分:1)

您还需要考虑from % 360 === to % 360时要执行的操作,例如

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)