Tuesday, March 1, 2011

finding angles 0-360

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

From stackoverflow
  • This should do the trick:

    1. If y2
    2. If < 0, add 360.

    Examples:

    (x1,y1) = 0

    (x2,y2) = (-1,1), atan() = -45, [add 360], 270
    (x2,y2) = (1,1), atan() = 45
    (x2,y2) = (1,-1), atan() = -45, [add 180], 135
    (x2 ,y2) = (-1,-1), atan() = 45, [add 180], 225
    
  • 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?

    Johnny Darvall : 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=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/180)),v=u
    jilles de wit : 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
  • Also note:

    if (y1==y2) {
        if (x1>x2)
            angle = 90;
        else if (x1<x2)
            angle = 270;
        else
            angle = 0;
    }
    
  • 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;
    }
    }
    
  • 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

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

0 comments:

Post a Comment