Angle between three points (2D): Simple code snippet.

posted 2014-Feb-11

Have three 2D points and want to find the angle between them? In JavaScript:

// Center point is p1; angle returned in radians
function findAngle(p0,p1,p2) {
  var a = Math.pow(p1.x-p0.x,2) + Math.pow(p1.y-p0.y,2),
      b = Math.pow(p1.x-p2.x,2) + Math.pow(p1.y-p2.y,2),
      c = Math.pow(p2.x-p0.x,2) + Math.pow(p2.y-p0.y,2);
  return Math.acos( (a+b-c) / Math.sqrt(4*a*b) );
}

If speed matters, you may be able to make that a little bit faster by not using Math.pow() and manually squaring the differences instead.

In Ruby, assuming points are [x,y] arrays instead of objects with .x and .y properties, and converting to degrees:

# p1 is the center point; result is in degrees
def angle_between_points( p0, p1, p2 )
  a = (p1[0]-p0[0])**2 + (p1[1]-p0[1])**2
  b = (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2
  c = (p2[0]-p0[0])**2 + (p2[1]-p0[1])**2
  Math.acos( (a+b-c) / Math.sqrt(4*a*b) ) * 180/Math::PI
end

Credit for the JavaScript function upon which I based my code comes from this Stack Overflow answer, though that version has unnecessary sqrt calls. Read the answers on that page for the derivation of the above formula.

net.mind details other résumé contact
Phrogz.net