Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding angles 0-360

Tags:

javascript

Need help with a math issue: i need to get the true angle from 0 degrees using x and y cordinates im using this at the moment:

Math.atan((x2-x1)/(y1-y2))/(Math.PI/180)

but /(Math.PI/180) limits results from -90 to 90 i need 0-360

note: I'm using the angle to indicate direction:

  • 0=up
  • 90=right
  • 135=45 degree right+down
  • 180=down
  • 270=left
  • etc
like image 432
Johnny Darvall Avatar asked Nov 10 '09 11:11

Johnny Darvall


2 Answers

The atan function only gives half the unit circle between -pi/2 and +pi/2 (0 on x axis), there is another library function that can give the whole unit circle between -pi and + pi, atan2

I would think you are better of using atan2 to get the right quadrant rather than branching yourself, then just scale as you have been, something like

Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI + 180

The multiply by 180 over pi is just the scale from radians to degrees as in the question (but with the division by a division simplified), the +180 makes sure its always positive i.e. 0-360 deg rather than -180 to 180 deg

like image 136
jk. Avatar answered Sep 18 '22 12:09

jk.


Math.atan limits you to the two rightmost quadrants on the unit circle. To get the full 0-360 degrees:

if x < 0 add 180 to the angle
else if y < 0 add 360 to the angle. 

Your coordinate system is rotated and inverted compared to mine (and compared to convention). Positive x is to the right, positive y is up. 0 degrees is to the right (x>0, y=0, 90 degrees is up (x=0,y>0) 135 degrees is up and to the left (y>0, x=-y), etc. Where are your x- and y-axes pointing?

like image 23
jilles de wit Avatar answered Sep 18 '22 12:09

jilles de wit