Reputation: 323
I have converted a c++ code into javascript which calculates angle between 3 points. Though it is working properly I do not understand math behind it.
function angle(a, b, c) {
var ab = { x: b.x - a.x, y: b.y - a.y };
var cb = { x: b.x - c.x, y: b.y - c.y };
var dot = (ab.x * cb.x + ab.y * cb.y); // dot product
var cross = (ab.x * cb.y - ab.y * cb.x); // cross product
var alpha = -Math.atan2(cross, dot);
if (alpha < 0) alpha += 2 * Math.PI;
return alpha;
}
What is the use of dot and cross product here? How does atan2 use cross and dot products to calculate angle?
Upvotes: 1
Views: 451
Reputation: 10458
var ab = { x: b.x - a.x, y: b.y - a.y };
var cb = { x: b.x - c.x, y: b.y - c.y };
these points represent the lines AB and BC. Now dot product of 2 lines is
dot = |AB|.|BC|.cos(theta)
cross = |AB|.|BC|.sin(theta)
their division would get
cross/dot = tan(theta)
so
theta = atan(cross, dot)
we know the value of dot and cross from
dot = (ab.x * cb.x + ab.y * cb.y);
cross = (ab.x * cb.y - ab.y * cb.x);
hence we can find the angle using the above information
Upvotes: 2