Saturday, April 30, 2011

XNA Tutorial (Part 1: Introduction)

Microsoft's XNA framework allows developers to create exciting games for the PC, Xbox360, Zune, and Windows Phone 7. In these tutorials I will explain how to use the XNA framework with Visual Studios and C#. I make the assumption that you are already familiar with programming, the C# language, and some version of Visual Studios (express edition is fine).

System Requirements

Once you have everything installed on your computer open up Visual Studios. Then navigate to file -> New Project. A new project dialog box will pop up. 

Select the Windows Game (3.1) template from the available project types and rename the solution if you like. Click ok and a new solution will be created for you. 

Creating a new Windows Game in Visual Studios Professional 2008
If you run the solution as is you will only get a window with a blue background. However the solution has all the basics you need to start writing your own video game.

Looking in the solution explorer we can see that by default XNA creates: two code files for us named Program.cs and Game1.cs, two image files Game.ico and GameThumbnail, and one special folder named Content. Program.cs is the entry point of the application and contains our Main() method. Game1.cs can be thought of as our games 'Engine', and as such I often rename the file to Engine.cs.  This file exposes many useful methods of XNA and will be the base we build our game on. The Content folder is a special folder in XNA that we will place all off our game assets in. Things like images, sounds, 3D models, effect files, bitmaps, spritefonts, etc.

By looking at the pseudo code below you should be able to get an understanding of the basic flow and logic of a XNA game.

Game1() - General initialization.
Initialize() - Game initialization.
LoadContent() - Load graphics resources.
Run() - Start game loop. Can be found in Program.cs.
    Update() - Get input, perform calculations, and check for game ending criteria. 
    Draw() - Render graphics.
UnloadContent() - Free graphics resources. Not used often in smaller projects. .Net takes care of freeing resources with garbage collection.

Understanding the concept of the game loop is important to understanding how XNA works. Unlike some business applications that are 'event based' and wait for user input before doing something, XNA must do something even when the user is not supplying input. .