1

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?

jonarya
  • 303
  • 1
  • 4
  • 16
  • Unit vectors enable two convenient identities: the dot product of two unit vectors yields the cosine (which may be positive or negative) of the angle between the two unit vectors. The magnitude of the cross product of the two unit vectors yields the sine (which will always be positive). – Robinson Aug 18 '17 at 10:38
  • what do you mean with "angle between 3 points" ? Maybe related: https://stackoverflow.com/questions/1211212/how-to-calculate-an-angle-from-three-points – 463035818_is_not_an_ai Aug 18 '17 at 10:38
  • 1
    https://math.stackexchange.com/questions/361412/finding-the-angle-between-three-points – 463035818_is_not_an_ai Aug 18 '17 at 10:39
  • as the question isnt really about code, it would be better at https://math.stackexchange.com/ It is not c++ **and** javascript at the same time anyhow – 463035818_is_not_an_ai Aug 18 '17 at 10:42
  • This is related to this answer https://stackoverflow.com/questions/3486172/angle-between-3-points – jonarya Aug 18 '17 at 10:45
  • That's not a cross product – the cross product is a vector and is only defined in three-dimensional space. – molbdnilo Aug 18 '17 at 10:57

1 Answers1

2
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

marvel308
  • 10,288
  • 1
  • 21
  • 32
  • 1
    The `theta = atan(cross, dot)` is actually `atan(cross/dot)`. In programming languages (or their libraries) like C and JavaScript, that is expressed in alternate form as `atan2(cross, dot)` which ensures an angle in the correct quadrant (and avoids problems of division by zero if `dot` is zero), to give a result between `-PI` and `PI` – Peter Aug 18 '17 at 11:15