Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  123] [ 6]  / answers: 1 / hits: 18484  / 14 Years ago, thu, july 22, 2010, 12:00:00

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 is at (10,5) - that would result in 90 degrees (as positive Y is down, negative Y is up)
(10,10) vs (10,15) would be 270 degrees.



How would I go about this?


More From » math

 Answers
245

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.


[#96145] Tuesday, July 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryley

Total Points: 118
Total Questions: 81
Total Answers: 102

Location: Kazakhstan
Member since Thu, Dec 23, 2021
2 Years ago
;