Sign in to follow this  
h3ro

Make a sprite always rotated against the mouse coursor?

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 this post


Link to post
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 this post


Link to post
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 face
face_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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this