Monday, April 6, 2015

2d - Set sprite to face direction of mouse


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 ?



Answer



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.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...