Zanrkvil
Zanrkvil

Reputation: 71

how to flip a sprite in c#

I'm making a little game based on XNA game development's tutorial game "shooter"... after a bit of trial and error, I made my own animated sprite that i can move around the screen. The problem is, he's always facing right.

How can i change this (image below) so that he faces the right direction every time the key event is pressed?!

I'm pretty new to C# as you might have guessed, and I realize this may be more complicated than i thought, so i just need to know how to make the sprite face right when moving right and left when he's moving left.

image

Thank you in advance.

Upvotes: 7

Views: 14734

Answers (3)

user1724717
user1724717

Reputation: 47

SpriteEffects s = SpriteEffects.FlipHorizontally;
int smX = 200; //smx is the 'x' coordinates.

    public void runChar()
    {
        if (Keyboard.GetState().IsKeyDown(Keys.Left))
        {
            smX -= 2;
            s = SpriteEffects.FlipHorizontally;
            //oposite direction.
        }
        else if (Keyboard.GetState().IsKeyDown(Keys.Right))
        {
            smX += 2;
            s = SpriteEffects.None;
            //original direction.
        }
    }

spriteBatch.Draw(sM, new Rectangle(smX, 200, 100, 100), null, Color.White, rotation, new Vector2(50, 50), s, 0f);

This will 'flip' the texture left and right.

Upvotes: 0

Bryan
Bryan

Reputation: 6699

You can also do this by passing the SpriteEffects.FlipHorizontally option to yourSpriteBatch.Draw() method. But as others have said this will have more overhead than using a sprite sheet.

Upvotes: 7

Ed Swangren
Ed Swangren

Reputation: 124642

Usually a sprite sheet will contain images for each direction. You can flip the image at runtime, but it adds image processing that is unnecessary. I would suggest to you that you simply create a sprite sheet up front with each animation baked in and just figure out which frame to display at runtime.

See an example of a simple sprite sheet here

Upvotes: 2

Related Questions