Jump to content
  • Advertisement
Sign in to follow this  

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.

If you intended to correct an error in the post then please contact us.

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

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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!