Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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).

Edit: 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.

share|improve this question
    
Hi there, I had a similar problem like you, with archery. Check out my blog, if you want: yannbane.blogspot.com. –  jco Nov 9 '11 at 16:36
    
possible duplicate of Orienting a model to face a target –  Nicol Bolas Apr 4 '12 at 21:09

1 Answer 1

up vote 8 down vote accepted

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.

share|improve this answer
2  
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. –  Nicol Bolas Nov 9 '11 at 5:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.