tags:

views:

229

answers:

5

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: im using the angle to indicate direction: 0=up 90=right 135=45 degree right+down 180=down 270=left etc

A: 
Gamecat
+4  A: 

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?

jilles de wit
like this? var add=0 var x=x2-x1 var y=y2-y1 if(x<0) add=180 else if(y<0) add=360 var u=parseInt((Math.atan((x2-x1)/(y1-y2))+add)/(Math.PI/3.1428)),v=u
Johnny Darvall
correction:var add=0var x=x2-x1var y=y2-y1if(x<0)add=180else if(y<0)add=360var u=parseInt((Math.atan((x2-x1)/(y1-y2))+add)/(Math.PI/180)),v=u
Johnny Darvall
No, add the number after you divide by (pi/180) otherwise add should be math.PI instead of 180 and 2*Math.PI instead of 360
jilles de wit
+1  A: 

Also note:

if (y1==y2) {
    if (x1>x2)
        angle = 90;
    else if (x1<x2)
        angle = 270;
    else
        angle = 0;
}
Paul Lammertsma
A: 
function angle(x1,y1,x2,y2)
{
eangle = Math.atan((x2-x1)/(y1-y2))/(Math.PI/180)
if ( angle > 0 )
{
  if (y1 < y2)
    return angle;
  else
    return 180 + angle;
} else {
  if (x1 < x2)
    return 180 + angle;
  else
    return 360 + angle;
}
}
syava
+3  A: 

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 s0mething like

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

jk
Yep, use the built in functions for what they were built in for.
High Performance Mark
Thanks a stack! This appears to produce the correct angles
Johnny Darvall
yes, this is better than my option.
jilles de wit