Calculating degrees between 2 points with inverse Y axis

前端 未结 4 1280
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 17:45

I\'m creating a simple 2D game in javascript/canvas. I need to figure out the angle of a certain object relative to my position.

So: say I\'m at (10,10) and the object i

4条回答
  •  萌比男神i
    2021-01-31 18:34

    Suppose you're at (a, b) and the object is at (c, d). Then the relative position of the object to you is (x, y) = (c - a, d - b).

    Then you could use the Math.atan2() function to get the angle in radians.

    var theta = Math.atan2(-y, x);
    

    note that the result is in the range [-π, π]. If you need nonnegative numbers, you have to add

    if (theta < 0)
       theta += 2 * Math.PI;
    

    and convert radians to degrees, multiply by 180 / Math.PI.

提交回复
热议问题