Public Group

# Make a sprite always rotated against the mouse coursor?

This topic is 3791 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hallo, Im trying to make my playere sprite rotate so that it is always facing mouse. But it only works when the mouse is to the left of the ship. What am I doing wrong? int differenceX = xPos - mouseXpos; int differenceY = yPos - mouseYpos; int rotation = (atan((float)differenceY/differenceX)) * 180 / 3.14159265;

##### Share on other sites
should use a float or double for rotation, for accuracy.

could try atan2(difY, difX), although i think it does the same thing..

i think atan gives out radians try atan + 90 * (PI / 180)
change 90 depending on clockwise/anti clockwise.

but don't listen to me.. i suck at maths and its been awhile since i asked the same question.

##### Share on other sites
double rotate = (Math.Atan2(mouseY-spriteY,mouseX-spriteX)/Math.PI)*180;//if the sprite is above the mouse point (BASED ON SCREEN CO-ORDINATES, NOT CARTESIAN)if (mouseY>spriteY)  rotate = 360 - rotate; //the heading to faceface_direction(rotate);

First we calculate the angle to rotate using atan2 (important to use ATAN2 not ATAN).

Then we establish if the point is above or below us (if using screen co-ordinates then the y axis value is decreasing as we approach the top of the screen) hence if spriteY<mouseY (above the mouse point), in which case you subtract the result from 360 degrees.

Now the KEY thing to note here is that the sprite is always considered to be facing east (0 degrees), this allows you to get a perfect calculation (it's totally irrelevant that the sprite is facing 0 to start with as he always snaps to the correct mouse facing anyway - so don't get confused by this).

The FACT that you start at 0 and face accordingly either +clockwise or -counterclockwise.

Example result might be 315 degrees, so you rotate from 0, -45degrees to face the mouse.

Bingo! :)

[Edited by - Pickl3d on February 28, 2008 11:13:14 AM]

##### Share on other sites
Erm I made quite a few edits to my original post, this is the correct version.

1. 1
Rutin
24
2. 2
3. 3
JoeJ
18
4. 4
5. 5

• 38
• 23
• 13
• 13
• 17
• ### Forum Statistics

• Total Topics
631706
• Total Posts
3001833
×