Reputation: 904
I have the following function, to find the angle between 3 points.
(Where a point is defined as an array containing the x position as its first element and the y position as its second element, and the angle to measure is the angle created when a line is drawn through all three points.)
findAngle: function(a, b, c) {
var ab = Math.sqrt(Math.pow(b[0] - a[0], 2) + Math.pow(b[1] - a[1], 2));
var bc = Math.sqrt(Math.pow(b[0] - c[0], 2) + Math.pow(b[1] - c[1], 2));
var ac = Math.sqrt(Math.pow(c[0] - a[0], 2) + Math.pow(c[1] - a[1], 2));
var o1 = (bc * bc + ab * ab - ac * ac) / (2 * bc * ab);
var o2 = Math.acos(o1);
var o3 = o2 * (180 / Math.PI);
return o3;
}
However, this only ever returns angles between 0 and 180 degrees. How can I have it return values between 0 - 180 degrees, and values between 180 and 360 when the angle is in fact obtuse?
Upvotes: 0
Views: 1027
Reputation: 80177
Use atan2 function that has two arguments and returns result in range -Pi..Pi
(add 2*Pi
to negative angles if needed)
angle = Math.atan2(crossproduct(c-b,b-a), dotproduct(c-b,b-a))
where
crossproduct(c-b,b-a) = (c.x-b.x)*(b.y-a.y) - (c.y-b.y)*(b.x-a.x)
dotproduct(c-b,b-a) = (c.x-b.x)*(b.x-a.x) + (c.y-b.y)*(b.y-a.y)
Upvotes: 1