9
\$\begingroup\$

I'm building a html5 canvas game and I need a way to get my sprite to face the mouse cursor. I have the X and Y co-ordinates for the sprite, and also the X and Y co-ordinates of the pointer. All I'm stuck with is the math involved to make the sprite face the pointer. It's all in a 2D world, so I can't imagine it'll be too complicated, but I have very little experience with this stuff.

Also any helpful links to articles/blog posts about this sort of thing would be awesome (2D game programming in general, not specifically Javascript).

To add, i should note that I need an angle in degrees that will point me towards the cursor using its X and Y position.

How can i know the co-ordinates of the cursor and where do i put all of this stuff ?

\$\endgroup\$
2

1 Answer 1

11
\$\begingroup\$

Not knowing the API's at your disposal, here's the basic math behind getting an angle in degrees:

angle = math.atan2(y2 - y1, x2 - x1) * 180 / math.pi;

The * 180 / math.pi; converts it from radians to degrees.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Note that the angle produced by atan2 assumes that the coordinate system is +x right and +y up. If yours goes down, then you will need to negate the angle. It also assumes that the object will be facing the (1, 0) direction (right) when the angle is 0. If it faces a different direction, then you need to offset the angle. My answer here explains how to do that. \$\endgroup\$ Commented Nov 9, 2011 at 5:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .