Incorrect angle, wrong side calculated

angle, javascript, math

Solution

HI there your math and calculations are perfect. Your running into the same problem most people do on calculators, which is orientation. What I would do is find out if the point lies to the left or right of the vector made by the first two points using this code, which I found from

Determine which side of a line a point lies

isLeft = function(ax,ay,bx,by,cx,cy){
 return ((bx - ax)*(cy - ay) - (by - ay)*(cx - ax)) > 0;
}

Where ax and ay make up your first point bx by your second and cx cy your third.

if it is to the left just add 180 to your angle

Problem

I need to calculate the angle between 3 points. For this, I do the following: - Grab the 3 points (previous, current and next, it's within a loop) - Calculate the distance between the points with Pythagoras - Calculate the angle using `Math.acos` This seems to work fine for shapes without angels of over 180 degrees, however if a shape has such an corner it calculates the short-side. Here's an illustration to show what I mean (the red values are wrong): This is the code that does the calculations: ``` // Pythagoras for calculating distance between two points (2D) pointDistance = function (p1x, p1y, p2x, p2y) { return Math.sqrt((p1x - p2x)*(p1x - p2x) + (p1y - p2y)*(p1y - p2y)); }; // Get the distance between the previous, current and next points // vprev, vcur and vnext are objects that look like this: // { x:float, y:float, z:float } lcn = pointDistance(vcur.x, vcur.z, vnext.x, vnext.z); lnp = pointDistance(vnext.x, vnext.z, vprev.x, vprev.z); lpc = pointDistance(vprev.x, vprev.z, vcur.x, vcur.z); // Calculate and print the angle Math.acos((lcn*lcn + lpc*lpc - lnp*lnp)/(2*lcn*lpc))*180/Math.PI ``` Is there something wrong in the code, did I forget to do something, or should it be done a completely different way?

Original source