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
Math.acos()
returns the interior angle, so becausecos
is an even function you need to subtract from2pi
to get the exterior angle.The following solves it by using the Math method
.atan2()
which returns results in the range from -PI to +PI: