I need to calculate the angle between 3 points. To do this, I do the following:
- Take 3 points (previous, current and next, within the loop)
- Calculate the distance between points using Pythagoras
- Calculate the angle using
Math.acos
It seems to be great for figures without angels more than 180 degrees, however, if the shape has such an angle, it calculates the short side. Here is an illustration to show what I mean (red values ββare wrong):

This is the code that performs 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
Something is wrong in the code, I forgot to do something, otherwise it will be completely different?
javascript math angle
Broxzier
source share