Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating degrees between 2 points with inverse Y axis

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?

like image 805
skerit Avatar asked Jul 22 '10 13:07

skerit


People also ask

How do you find the angle of rotation between two points?

The angle of rotation between the two points or vertices is the number of central angles times the measure of a single central angle: angle of rotation =m×α = m × α .


2 Answers

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.

like image 62
kennytm Avatar answered Oct 23 '22 05:10

kennytm


If your coordinates are (xMe, yMe) and their coordinates are (xThem, yThem), then you can use the formula:

arctan((yMe-yThem)/(xThem-xMe))

Normally it'd be arctan((yThem-yMe)/(xThem-xMe)), but in this case the sign of the y-axis is reversed.

To convert the result from radians to degrees multiply by 180/pi.

So in JavaScript, this would look like: Math.atan((yThem-yMe)/(xThem-xMe))*180/Math.PI

atan gives a value between -pi/2 and pi/2 (that is, between -90 and 90 degrees). But you can look at what quadrant your (xThem - xMe, yMe - yThem) vector is in and adjust accordingly.

like image 40
Tim Goodman Avatar answered Oct 23 '22 06:10

Tim Goodman