Home > database >  JavaScript - Find turn direction from two angles
JavaScript - Find turn direction from two angles

Time:11-13

I have two normalized angles (between 0 and 360 degrees) and i want to find the shortest turn direction from point a to point b. (clockwise or counterclockwise). a or b can be anywhere on the circle, so the function should work in both way: if a is smaller and if a is larger than b.

I am wrote the following function, which works fine except when the shortest distance crosses the 0 degree mark:

function clockwise(a, b){

    return a < b;     

}

The function return true if it is clockwise and false if the direction is counterclockwise.

How can I get this to work for distances that cross the 0 degree angle? I am looking for an implementation specifically in JavaScript, since I wasn't able to translate any of the mathematical explanations I found. Thanks in advance!

enter image description here

CodePudding user response:

Relative to point a,

  • Is clockwise, If b is present is in the next 180
  • anticlockwise otherwise
function clockwise(a, b){
    let theta1 = b-a;
    return theta1 >= 0 && theta1 <= 180; // return true if clockwise
}

CodePudding user response:

There's probably a more elegant solution, but I think this gives the expected results?
(if a=60, b=230 the difference is 170 and clockwise=true is correct..?!)

function clockwise(a, b) {
  let clockwise, diff
  if (b > a) {
    diff = b - a
    clockwise = diff >= 0 && diff <= 180
  } else {
    diff = a - b
    clockwise = diff >= 180
  }
  return clockwise
}

console.log(clockwise(60,230))  // true
console.log(clockwise(220,150))  // false
console.log(clockwise(40,300))  // false
console.log(clockwise(120,214))  // true
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related