Inverse of math.atan2?

前端 未结 4 801
面向向阳花
面向向阳花 2021-02-07 06:46

What is the inverse of the function

math.atan2

I use this in Lua where I can get the inverse of math.atan by math.tan

4条回答
  •  醉话见心
    2021-02-07 07:10

    You'll probably get the wrong numbers if you use:

    local dy = y1-y2 
    local dx = x1-x2
    local angle = atan2(dy,dx) * 180 / pi
    

    If you are using the coordinate system where y gets bigger going down the screen and x gets bigger going to the right then you should use:

    local dy = y1 - y2
    local dx = x2 - x1
    local angle = math.deg(math.atan2(dy, dx))
    if (angle < 0) then
      angle = 360 + angle
    end
    

    The reason you want to use this is because atan2 in lua will give you a number between -180 and 180. It will be correct until you hit 180 then as it should go beyond 180 (i.e. 187) it will invert it to a negative number going down from -180 to 0 as you get closer to 360. To correct for this we check to see if the angle is less than 0 and if it is we add 360 to give us the correct angle.

提交回复
热议问题