0
votes

I'm trying to calculate the angle between a still and moving vector in javascript. However, I want the angle to be additive based on direction (so if you're moving clockwise, the angle would always increase, whereas moving counterclockwise would cause the angle to only decrease).

I'm storing the coordinates in arrays as start[x, y] and current[x,y] and need to calculate the angle while the current array changes. I'm also currently using the atan2 function, but this is limited to -180 to +180 degrees.

start = [event.clientX - discCent[0], event.clientY - discCent[1]];
current = [event.clientX - discCent[0], event.clientY - discCent[1]];

// Get this to be additive
angleDeg = Math.atan2(current[1] - start[1], current[0] - start[0]) * 180 / Math.PI;

Thanks!

1

1 Answers

0
votes

Keep the previous angle and add/subtract a multiple of 360° to get closest to it:

var angleDegPrev = 0.; // initialization at start
...

// compute angle in ]-180,180]
start = [event.clientX - discCent[0], event.clientY - discCent[1]];
current = [event.clientX - discCent[0], event.clientY - discCent[1]];
angleDeg = Math.atan2(current[1] - start[1], current[0] - start[0]) * 180 / Math.PI;

// add multiple of 360 to get closest to previous angle
angleDeg += Math.round((angleDegPrev - angleDeg)/360.)*360.;
angleDegPrev = angleDeg;