Bill Reiss is a Windows Platform Development MVP and a Senior Consultant for AgileThought

Intro to XNA on Windows Phone Part 3

At the end of Part 2 of this series, we had our character running in place. image_thumb5

This was done through the Update method of the XNA Game class processing when the frame should change, and then the Draw method called the appropriate SpriteBatch.Draw method to draw the current frame. Here is the source code that we’ll start with and build upon in this post.

This is a fairly short one, we just need to build upon some of the topics so far to build a platform for our player to run on, and then we’ll be done with Step 1 (“Draw Stuff”) of building an XNA game.

Here is the platform image:


Click on the image and then select to save it to your computer. Call it platform.png.

Now just like with the player image from Part 1, add an existing item to the content project. This time we’ll use platform.png. Now we want to do exactly the same thing we did before, adding a field to store the texture, and a couple of others to store the animation state:

Texture2D platform;
float platformOffset = 0;
float platformScrollSpeed = 200;

And in LoadContent we’ll load it:

platform = Content.Load<Texture2D>("platform");

And then in the Draw method we’ll draw a row of these under the player:

for (float f = -platformOffset; f < 800; f += platform.Width)
    spriteBatch.Draw(platform, new Vector2(f, 300 + runFrameHeight),

Notice that you can use the same texture multiple times when drawing. This is starting to look better:


Now to give an illusion of motion we can scroll the platform by changing the platformOffset in the Update method based on the speed and the elapsed time:

platformOffset += platformScrollSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
if (platformOffset > platform.Width) platformOffset -= platform.Width;

Every time we scroll more than the width of a block, we’ll subtract the width of the block from the offset so that the number doesn’t keep getting bigger, but since we shift by exactly the width of one block the motion looks smooth and continuous.

Run it again. You should now see the running man and the scrolling platform. Not bad for less than 40 lines of code.

Here is the source code for the project at this point:

In the next post we’ll start Step 2 and look at how to handle input in XNA.