Nuffnang Ads

Thursday, 14 June 2012

XNA 2D game tutorial - animated sprite

1. Initialize state and time (continue from the XNA 2D games static sprite tutorial)
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D character;
Vector2 position = new Vector2(200, 200);
Point frameSize = new Point(28, 41);
Point currentFrame = new Point(1, 0);
Point sheetSize = new Point(12, 8);
int state = 1; // 1 = walking state
TimeSpan nextFrameInterval = TimeSpan.FromSeconds((float)1 / 16);
public Game1()
{
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
           TargetElapsedTime = new TimeSpan(0, 0, 0 , 0, 100);
            // means, frame will be updated every 100ms.
  }

2. Now we want our character to be automatically at the walking position and animating. Go to update method and add this :
protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();           
            if (state == 1) // means walking state
           {
                currentFrame.Y = 2;
                currentFrame.X++;
                if (currentFrame.X >= 12)
                    currentFrame.X = 0;
            }
            base.Update(gameTime);
        }

3. Code explaination
currentFrame.Y = 2;
// for the walking state, we will use row number 2.
currentFrame.X++;
if (currentFrame.X >= 12)
 currentFrame.X = 0;
// in the row number 2, there are 12 characters and it will move one by one until the last character and it will loop back from the character number 0.

4. Run the code
    -Build (Shift+F6) and Run (Ctrl+ F5).žThe walking mario will appeared. 



1 comment: