skip to Main Content

I am getting the angle of two vectors.

code returns

90 = 1.57 
180 = 3.14

It’s ok,however

270 = 1.57

This would be the same 90, I want to distinguish 90 / 270.

Where should I fix?

getAngle(a,b){

    var dot = a.x * b.x + a.y * b.y;

    var absA = Math.sqrt(a.x*a.x + a.y*a.y);
    var absB = Math.sqrt(b.x*b.x + b.y*b.y);

    var cosTheta = dot / (absA*absB);

    var theta = Math.acos(cosTheta);
    
    console.log("force theta:",theta);
    return theta;
}

2

Answers


  1. Math.acos() returns the interior angle, so because cos is an even function you need to subtract from 2pi to get the exterior angle.

    var theta = 2*Math.PI - Math.acos(cosTheta);
    
    Login or Signup to reply.
  2. The following solves it by using the Math method .atan2() which returns results in the range from -PI to +PI:

    const dot=(a,b)=>a.x*b.x+a.y*b.y,
            x=(a,b)=>a.x*b.y-a.y*b.x
          ang=(a,b)=>Math.atan2(x(a,b),dot(a,b))*180/Math.PI,
          // a few sample vectors:
          a={x:2,y:2},b={x:-3,y:3},c={x:-4,y:0},d={x:0,y:-5};
    
    console.log(ang(a,b));
    console.log(ang(a,c));
    console.log(ang(a,d));
          
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search