Search code examples
javascriptmathvectorangle

Getting the angle from 3 vectors, without excluding non-reflex of obtuse angles


So I struggled last two days and found many answers but I have modified one

findAngle(c, b, a) {

    const ab = {x: b.x - a.x, y: b.y - a.y};
    const cb = {x: b.x - c.x, y: b.y - c.y};

    const dot = (ab.x * cb.x + ab.y * cb.y); // dot product
    const cross = (ab.x * cb.y - ab.y * cb.x); // cross product

    let alpha = Math.atan2(cross, dot);
    if (alpha < 0) {
      alpha = (Math.PI * 2 + alpha);
    }
    return alpha;
}

im not sure its right, I don't like the alpha < 0 portion can anyone suggest a better opinion


Solution

  • // assuming that b is the point at which you want to find the angle (formed by vectors bc and ba) 
    const angle = (c, b, a) => {
      const bc = {x: c.x - b.x, y: c.y - b.y};
      const ba = {x: a.x - b.x, y: a.y - b.y};
      // the cosine of the angle between the two vectors is their dot product divided by the product of their magnitudes
      const cos = (bc.x * ba.x + bc.y * ba.y) / (Math.hypot(bc.x, bc.y) * Math.hypot(ba.x, ba.y));
      // return the angle in degrees
      return 180 * Math.acos(cos) / Math.PI;
    }
    console.log(angle({x: 3, y: 4}, {x: 0, y: 0}, {x: -3, y: -4})); // the angle between two opposite vectors
    console.log(angle({x: 0, y: 4}, {x: 0, y: 0}, {x: 4, y: 0})); // the angle between two perpendicular vectors
    console.log(angle({x: 3, y: 4}, {x: 0, y: 0}, {x: 4, y: 3}));