XNA 2D Game Tutorial (Part 1)

November 1, 2010

2 comments

I like creating games. In fact, that’s what drew me into the computer world back in 1983. It’s amazingly satisfying seeing one of your creations looking like it’s alive, making decisions and reacting to the player’s actions. Back then I used to create games for the legendary Commodore 64, with it’s 64KB of RAM (of which about 39K was free for the programmer), 1MHz 6510 CPU (yes, 1 mega-hertz!), its video chip (VIC) that supported 8 hardware sprites (more on that in a bit) and its sound chip (SID) that supported 3 independent voices including white noise. It was a mean gaming machine for its time, leaving computers such as Apple II and ZX Spectrum eating dust.

Days and years went by… the PC took over all other machines, mainly because of its open architecture. Now fast forward to 2010. We have monstrous CPUs and GPUs, the latter capable of handling many graphic tasks that used to be handled by CPUs alone.

There are many libraries and frameworks for writing games these days. Most of them are capable graphic engines, written in C++ for C++ consumption. There are others, however. One of them is the Microsoft XNA framework, born a few years back and now in it’s 4th major version. This framework allows programming games in .NET, targeting the PC, XBox 360, Zune (up until version 3.1) and now the Windows Phone 7, all with high source code compatibility.
Although Windows Phone 7 is the big hype at the moment, I want to present a tutorial that uses the plain old PC as the gaming platform. Changing it to WP7 or XBOX is not too difficult and maybe I’ll tackle that in the last part of this series. Note that there are plenty of tutorials out there… but this is mine.

Getting started

To get started, you’ll need Visual Studio 2010 (any edition, including Express), XNA Game Studio 4, and (if you want to develop for Windows Phone 7) the tools for Windows Phone 7. All these are free downloads (VS 2010 express version only), so go ahead and download and install the bits.

Open VS 2010 and select File->New Project. In the new project dialog box, navigate to Visual C#. You should see a sub-node named XNA Game Studio 4.0. Select the Windows Game (4.0) option in the right side and enter a name for the project. We’ll call it AlienRaid and it will be a pretty classic shooter, that will allow me to show XNA stuff, while walking in familiar territory. This will be a 2D game (I may tackle 3D in a later time) – don’t underestimate 2D – we can create fun games with whatever technology or game type!

The complete game will look something like this:

SNAGHTML38952709

The dialog box should look something like this:

image

Click OK.

You’ll see 2 projects created, named “AlienRaid” and “AlienRaidContent”. We’ll get to the reason for the two projects later. The main project hosts the Game1.cs file. For now, just press F5 or Ctrl+F5 to run the game. If everything is setup ok you should see something like this:

image

Not an amazing game yet, but it’s a start!

Notice that the mouse cursor disappears when hovering over the window. Close the window using the X button or press Alt+F4.

Let’s explore some of the code generated by the wizard. The Game1.cs class hosts a Game1 class inheriting from the XNA Game class. This is the main class of any XNA game. A single instance of it is created in the Main method (look at program.cs):

static void Main(string[] args) {

   using(Game1 game = new Game1()) {

      game.Run();

   }

}

The Run method only returns when the game exits.

First, we’ll do some simple refactoring and change the name of the game class to something more appropriate. In the Solution Explorer, rename Game1.cs to AlienRaidGame.cs. This will also change the class name from Game1 to AlienRaidGame.

Every game must have a game loop. A game loop is some code that’s run over and over again, each and every frame at some frame rate. XNA uses 60 frames per second (FPS) by default. That means the game loop runs every 16.66667 milliseconds. Where is the game loop located? That’s the two methods named Update and Draw of the game class.

First, let’s look at Draw:

protected override void Draw(GameTime gameTime) {

   GraphicsDevice.Clear(Color.CornflowerBlue);

 

   // TODO: Add your drawing code here

 

   base.Draw(gameTime);

}

 

Right now, it doesn’t do very much. The first instruction simply clears the drawing buffer to some color (that’s the color in the previous snapshot). If we are to create a space shooter, we probably want a black background, so let’s change the color to black:

GraphicsDevice.Clear(Color.Black);

 

Run the game and note the black background.

Generally, the Draw method is the placing all drawing code that’s needed to render the scene. This means the player’s ship, the alien enemies, the score, the various projectiles – everything must be drawn somewhere within this method. And it’s all drawn 60 times a second! This is how a game works. A game is never idle. It’s always doing something.

We still haven’t drawn anything… we’ll do that in part 2.

Let’s examine the Update method:

protected override void Update(GameTime gameTime) {

   // Allows the game to exit

   if(GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

      this.Exit();

 

   // TODO: Add your update logic here

 

   base.Update(gameTime);

}

 

The first thing happening is the checking of the XBOX game pad for a Back button press, and if pressed, the game exist by calling the Game.Exit method. Since we’re using the PC, we may not have a game pad available, let’s add code that exits the game when the ESC key is pressed. We can replace the existing code or simply add to it, so that both options are available.

To accomplish this, we’ll use the Keyboard.GetState static method, that will allow us to examine the state of any key we desire:

if(Keyboard.GetState().IsKeyDown(Keys.Escape))

   Exit();

 

The code tests to see if ESC is pressed and if so, calls the Exit method. Nothing to it!

What is that GameTime object we’re getting in Update and Draw? This object has two uses: the first, it indicates how much time has passed since the last call (to Update or Draw) in the ElapsedGameTime property (of type TimeSpan). These allows for timing thing more accurately, regardless of the actual frame rate. We’ll see examples of this in a later part. The second use is the IsRunningSlowly property. If true, it indicates XNA can’t keep up with the desired frame rate, so it may call Update more times (and not call Draw) to compensate. This is an advanced property and we won’t deal with it now. In a typical 2D game, it should be rare to get to a slowly running game, and even if we do get there, it’s usually very temporary.

In the next part we’ll start drawing something. Until then, the resulting project is attached.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

2 comments

  1. MadaraNovember 1, 2010 ב 20:27

    when you’ll post Part 2? thanks

    Reply
  2. blogs.microsoft.co.ilJune 21, 2011 ב 15:31

    Xna 2d game tutorial part 1.. Awesome :)

    Reply