Public Group

# Moving a Sprite in a certain Direction

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

## Recommended Posts

Most of my games have been simple 2d games and depending on the game, they generally had the same control scheme: Left/Right Arrows change your X position. Up/Down Arrows change your Y position. But now I am wanting to make it so that the character uses Up/Down to move forward/backward and Left/Right to rotate his direction. I know im going to need a direction variable (im guessing in degrees) and modify it using left/right, I just dont know to move the player in the direction instead of directly modifying X and Y. Thanks

##### Share on other sites
You will need to use some trigonometry to convert the rotation to x and y positions.

Like this:
x += (float)sin((M_PI / 180.0f) * (360.0f - rotation));y += (float)cos((M_PI / 180.0f) * (360.0f - rotation));

If you want a better explanation just ask.

##### Share on other sites
Thanks Homer.

I am using SFML which internally keeps the rotation of the sprite. This is good because I dont have to handle the bounds of degrees (0 to 360). So I am using your formulas for when the player presses Up and Down. Then for Left and Right, I am using SFML's SetRotation method and then doing GetRotation so that I also have the value of rotation so that I can use it with the formulas you gave me. BUT this doesnt work 100%. It starts off fine when you start out the game and are facing 180 degrees (straight up). But say I press the keys to go up and left, the sprite faces the correct direction, but the player moves north and RIGHT instead of left.

I was thinking the mapping of the degrees is different between the formula and SFML? Though going straight up and down works. Its just mirrored horizontally it seems.

##### Share on other sites
Now I feel dumb. :)

I fixed it by multiplying my value of rotation by negative one.

Any explanation on why exactly I had to do that?

My guess is that one of them works clockwise and the other counterclockwise or something in that manner.

##### Share on other sites
Quote:
 Original post by Falling SkyNow I feel dumb. :)I fixed it by multiplying my value of rotation by negative one.Any explanation on why exactly I had to do that? My guess is that one of them works clockwise and the other counterclockwise or something in that manner.

I don't know how SFML works as I've never used it. But your explanation seems accurate.

Have a look here for the definition of ::SetRotation().

1. 1
2. 2
3. 3
4. 4
Rutin
13
5. 5

• 25
• 10
• 9
• 9
• 11
• ### Forum Statistics

• Total Topics
633695
• Total Posts
3013374
×