Best viewed in Firefox

Awesty Productions

XNA Sidescroller Part 1

December 26th, 2007 by awesty

kick it on DotNetKicks.com kick it on GameDevKicks.com

This is the first of a series of tutorials that will help you make a sidescroller (like the old mario games) using XNA Game Studio. If you haven’t already install XNA Game Studio 2.0. If you are still using XNA 1.0 you will need to upgrade for this tutorial.

Open up XNA GSE and start a new project. Select “Windows Game” and give it any name you want. When you click OK ‘Game1.cs’ should be on your screen. It might look a little intimidating at first so I will explain what we will be using.

The LoadContent() function is where we will load all our graphics. The Update() function runs 60 times a second, and we will put everything that needs to be updated every frame in here. The Draw() function also runs 60 times a second and we will be drawing everything to the screen from here. Why can’t we just draw everything from the Update() function you may ask? If the game is running slowly Draw() will stop running everyframe because of that, but the Update() function will continue to run at 60fps.

Find the Game1() function and change it to this:

       public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferredBackBufferHeight = 608;
            graphics.ApplyChanges();
        }

That is just so the tiles will fit in the stage window nicely.

Before we get started we are going to need some graphics. Since this game is going to be tile based we will need a few tiles and a character. I have made three 32×32 pixel tiles. A black one for the ground, a red one that will kill the character and a yellow one that will take the character to the next level. I just made the character a 32×32 square. You can make him look better if you want but try and keep it 32×32 pixels, otherwise you will have to change some of the code. Save all those images into the Content folder of your game.

Go back into Visual Studio and open the solution explorer (View > Solution explorer). Right click on Content and select ‘Add > Existing Item’. Choose the 4 images we just made to add them to the project. Now we can start coding.

At the top of Game1.cs underneath the line that says SpriteBatch spriteBatch;, add this code:

        Texture2D blackTileTex;
        Texture2D redTileTex;
        Texture2D yellowTileTex;
        Texture2D playerTex;

We will use these Texture2D objects to draw the images to the screen. Scroll down to the LoadContent() function and underneath the line that says spriteBatch = new SpriteBatch(GraphicsDevice); add this:

blackTileTex = Content.Load<Texture2D>("black_tile");
            redTileTex = Content.Load<Texture2D>("red_tile");
            yellowTileTex = Content.Load<Texture2D>("yellow_tile");
            playerTex = Content.Load<Texture2D>("player");

This loads each images that we just made. Change “black_tile”, “red_tile”, “yellow_tile” and “player” to whatever you called your images.

We will make the levels using an array of numbers, where 0 will be a blank tile, 1 will be a black tile, 2 will be a red tile, 3 will be a yellow tile and 4 will be the players spawn point. We will make a separate class to hold all the level data so Game1.cs doesn’t get too messy. Open the solution explorer and select your project (it should be second from the top). Right click on it and select Add > New Item. Choose ‘Class’ and name it Levels (it’s case sensitive).

The new class should appear on your screen. You can switch between Game1.cs and Levels.cs by clicking the tabs above the code area. Between the curly braces for class Levels add the line public static int level1;. This array will hold our test level. It is public so we can access it outside the class and it is static so we don’t need to make a Levels object to access it. Add a new function to the class called Initialize.

       public static void Initialize()
        {
        }

Now go back to Game1.cs and find Initialize(). Above where it says base.Initialize(); put Levels.Initialize();. Now let’s make our first map. go back to Initialize() in the Levels class and put this code inside its curly braces:

           level0 = new int[,]{{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
            {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,1},
            {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,1},
            {1,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1},
            {1,0,0,0,0,0,0,0,0,1,1,1,2,1,1,1,1,1,1,3,1,1,1,1,1},
            {1,0,4,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}};

That may look a lot more confusing than it is. Every 1 represents a black tile, each 2 represents a killing (red) tile and each 3 represents a yellow tile. The 4 is the players spawn point. We will loop through each tile and check which one it is, and then draw the appropriate image to the screen. Go back to Game1 and find Draw();. Underneath where is says graphics.GraphicsDevice.Clear(Color.CornflowerBlue); add this:

spriteBatch.Begin();

            for(int i = 0; i < Levels.level0.GetLength(0); i++)            
                for(int j = 0; j < Levels.level0.GetLength(1); j++)
                {
                    if (Levels.level0[i, j] == 1)
                        spriteBatch.Draw(blackTileTex, new Vector2(j * 32, i * 32), Color.White);
                    if (Levels.level0[i, j] == 2)
                        spriteBatch.Draw(redTileTex, new Vector2(j * 32, i * 32), Color.White);
                    if (Levels.level0[i, j] == 3)
                        spriteBatch.Draw(yellowTileTex, new Vector2(j * 32, i * 32), Color.White);
                }

            spriteBatch.End();
 

We have to prepare the graphics device by putting spriteBatch.Begin(); before we draw anything, and restore the device to its previous state after we have finished drawing with spriteBatch.End();.

Between those two functions we have two for loops. One which loops through each row of tiles and another which loops through each tile in that row. Next we have three if statements checking what the value of the tile is, and draw the correct image to the screen using spriteBatch.Draw(Texture2D, Vector2, Color);. Note that the first row and first tile are at position 0, not 1. We draw the tile to the position of (j *32, i * 32). If the tile is 3rd from the left on the second row (i = 1, j = 2) it will be drawn at (64, 32).

If you press F5 or go to Debug > Start Debugging you can test out your game so far. You should see a map like this:

You might notice that you can’t see that character. That is because if we want the character to move around we can’t draw him at his spawn point every frame. We will fix that up in the next tutorial.

Click here to download the source files.

If you enjoyed this tutorial please kick it.

kick it on DotNetKicks.com kick it on GameDevKicks.com

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • del.icio.us
  • digg
  • Furl
  • MyShare
  • NewsVine
  • Netscape
  • Reddit
  • Simpy
  • Slashdot
  • StumbleUpon
  • Technorati
  • YahooMyWeb

RSS feed | Trackback URI

13 Comments »

Comment by Samuel
2007-12-30 07:18:29

First one here…I would like flash tutes and HitTest is my fav.!

 
Comment by Cbrown Subscribed to comments via email
2008-01-01 09:53:53

I having some trouble, for some reason my tiles aren’t loading

Comment by awesty Subscribed to comments via email
2008-01-01 12:40:21

Did you import them into the content folder?

Are you using XNA 2.0?

Did you put in the right name? You aren’t supposed to have the file extension in the content.Load<Texture2D>("somename");

 
 
Comment by Cbrown Subscribed to comments via email
2008-01-01 15:58:12

I don’t have the file extension.

Comment by awesty Subscribed to comments via email
2008-01-01 16:55:05

Try download the source code and see if there are any differences.

 
 
Comment by Joey Subscribed to comments via email
2008-01-02 12:29:29

ive got errors:
’side scroller.Levels’ does not contain a definition for ‘level0′ that comes up 5 times and then The name ‘level0′ does not exist in the current context

Comment by awesty Subscribed to comments via email
2008-01-02 13:02:44

Well that means the level0 doesn’t exist, which it should.

 
 
Comment by Cbrown Subscribed to comments via email
2008-01-03 07:27:01

Oh I found the problem. It was stupid. I forgot to add the images. I just placed them into the photo manually.

 
2008-01-08 22:48:59

[…] XNA Sidescroller Part 1 […]

 
Comment by MKA Subscribed to comments via email
2008-01-30 04:36:36

I got this when I tried f5. I downloaded the sourcecode and they’re completely Identical… what’s the problem?
http://i143.photobucket.com/al.....roblem.jpg

also, when I click “ok”, this comes up at the bottom:
Error 1 The type or namespace name ‘Game1′ could not be found (are you missing a using directive or an assembly reference?) C:\Users\Mike\Documents\Visual Studio 2005\Projects\WindowsGame2\WindowsGame2\Program.cs 12 20 WindowsGame2
Error 2 The type or namespace name ‘Game1′ could not be found (are you missing a using directive or an assembly reference?) C:\Users\Mike\Documents\Visual Studio 2005\Projects\WindowsGame2\WindowsGame2\Program.cs 12 37 WindowsGame2

 
Comment by Conrad Subscribed to comments via email
2008-06-03 10:09:31

Hello the only problem ive had so far is i cannot find the class Initialize
Add a new function to the class called Initialize.
public static void Initialize()
{
}

Comment by Conrad Subscribed to comments via email
2008-06-03 10:31:42

ok fixed that prob but the problem now is that it is not recognizing the void command line

 
 
Comment by Clow Subscribed to comments via email
2008-09-22 23:23:35

Hello I’m having a strange problem i seem to be getting a error saying
‘test side scroller.Levels’ does not contain a definition for ‘level0′
it says that 5 times then its follwed by it does not exist in context

I’m just not sure what the problem could be I’m sure i’ve followed the guide on key maybe i placed something in the wrong area?

 
Name (required)
E-mail (required - never shown publicly)
URI
Subscribe to comments via email
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> in your comment.