28

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?

skerit
  • 19,365
  • 23
  • 96
  • 139

4 Answers4

39

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.

kennytm
  • 491,404
  • 99
  • 1,053
  • 989
6

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.

Tim Goodman
  • 22,127
  • 7
  • 60
  • 81
  • 2
    I actually like KennyTM's answer better. Math.atan2 will know which quadrant you're in already, so you're spared the last step. – Tim Goodman Jul 22 '10 at 14:19
  • I still found this answer useful, it's a nice alternative because I want to control the quadrants my self. – Partack Jun 25 '14 at 19:39
4

In layman's terms:

function pointDirection(x1, y1, x2, y2) {
    return Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
}
Petah
  • 44,167
  • 27
  • 153
  • 209
1

In HTML5 canvas the origin is the top left corner hence the y axis grows from top to bottom. So regardless of wherever you are on the unit circle to calculate the angle of point A to the center(C) you should in fact do like

angle = Math.atan2(Cy-Ay,Ax-Cx)

and you will get your result in the range of [-π, π].

I have no idea why they haven't made the canvas origin the bottom left corner.

Redu
  • 22,595
  • 5
  • 50
  • 67