Introduction to XNA Game Studio

XNA

XNA

This article will step you through the process of getting started with XNA. I will show how to setup a new project using XNA Game Studio. This article is the basis for the following articles regarding XNA development.

Introduction

XNA Game Studio is a great way for beginning game developers to start creating games quickly. XNA is built on the .NET framework which allows you to develop games relatively easily in C#.

The MSDN App Hub provides articles, code samples, and tutorials for getting started with XNA (and Windows Phone 7 development). There is a lot of information there to get you started – so much information in fact that you may seem overwhelmed and not have a clear idea of where you should actually start. This tutorial series will try to break-down the difficult process of getting started as a game developer and get you up and running as quickly as possible.

Dependencies

Before we can start developing an XNA Game title, we need to make sure we have a few software packages installed.

  1. Visual Studio 2010: Visual Studio 2010 is the current development environment from Microsoft. If you want to develop XNA games using the XNA Game Studio 4.0, then you will need to have Visual Studio 2010. If you are a student in higher education, then you probably have access to Dreamspark (www.dreamspark.com) where you can download Visual Studio 2010 Professional for free. Otherwise, you can download the Visual Studio 2010 Express editions. Most likely, you will want to get the All-in-One ISO if you are unsure which version you should download.
  2. XNA Game Studio: XNA Game Studio 3.1 will work if you have Visual Studio 2008. If you want to use XNA Game Studio 4.0, you will need to have Visual Studio 2010.

Getting Started

You will need to have either Visual Studio 2008 or Visual Studio 2010 installed before you can start developing games using XNA Game Studio. I will not describe the process of installing the Visual Studio development environment in this article because it is probably slightly different for each version of Visual Studio.

  • If you have Visual Studio 2008 then you will need to download and install XNA Game Studio 3.1.
  • If you have Visual Studio 2010 then you will need to download and install XNA Game Studio 4.0.

In this article, I will be using Visual Studio 2010 and XNA Game Studio 4.0 but everything I show here should be applicable to Visual Studio 2008 and XNA Game Studio 3.1. If something is specific to XNA Game Studio 4.0, I will try to provide an alternative for those using XNA Game Studio 3.1. But hopefully this case is very rare.

Creating A New Project

Before we can start developing the next-gen state-of-the-art blockbuster game, we need to create a new game project in Visual Studio.

Launch Visual Studio and select “File -> New -> Project…” from the main menu.

Visual Studio 2010 - Add New Project

Visual Studio 2010 - Add New Project

You will be presented with the New Project dialog box shown below.

Visual Studio 2010 - New Project Dialog

Visual Studio 2010 - New Project Dialog

From the “Templates” pane, expand the “Visual C#” option and select “XNA Game Studio 4.0” template option as shown in the image above. For Visual Studio 2008 users, you will select the “XNA Game Studio 3.1” template option.

The right-pane will display the available project templates that you can choose from. Choose the “Windows Game” template to create a new game project.

If you have XNA Game Studio 4.0 installed, you will also see templates for Windows Phone Game and Windows Phone Game Library. Usually you will first create a Windows Game even if you want to target this device. Later when you are ready to deploy your game to the phone platform or the XBox 360 platform, you will convert your Windows Game project to a project that targets one of these platforms.

Converting your Windows Game project to target one of these two platforms is beyond the scope of this article but I would like to create an article later that deploys a Windows Game to the XBox 360 platform.

Choose a name for your new project in the “Name” text field, a location where the new solution should be stored in the “Location” field, and optionally, you can specify a different name for the created solution in the “Solution name” field.

Press the big scary “OK” button when your ready to create the future of video games.

Depending on what version of XNA Game Studio (and thus Visual Studio) you are using, you will be presented with a different view of the initial project in the solution explorer.

Visual Studio 2010 - Create New Project

Visual Studio 2010 - Create New Project

In the screenshot shown above, you will see that the project template has created two new projects, the Game project and the Content project. If you are using Visual Studio 2008 and XNA Game Studio 3.1, then the Content project will be a sub-project of the Game Project. As of XNA Game Studio 4.0, the Content project is a separate project in the solution.

Your new Game project will have a few default files available to you:

  • Game1.cs: This file contains the main game class which defines the logic of your game. This is the file that you will most likely be working with when you program your game.
  • Program.cs: This file contains the main entry-point for your game. An instance of your main game class (Game1.cs) will be instantiated and run from here. Unless you need to do some special initialization code before the game class is instantiated, you will usually not make any modifications to the Program.cs file.

At this point, you can already run the newly created game project. To run the game, select “Debug -> Start Debugging” (F5). You should be presented with a window with a cornflower-blue background.

XNA Game - Empty Game

XNA Game - Empty Game

Although not very interesting, you do have the beginnings of a potentially beautiful creation.

The Game Class

Let’s take a closer look at the Game1 class.

The first thing you may notice are the using statements at the beginning of the file.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

These statements will add these packages to the compilation paths so that you have access to the classes referenced in these packages in your source code. But where are these packages coming from? If you look at the Game project in the solution explorer, you will see a node called “References” in the tree view. If you expand the “References” node, you will see a list of assemblies that have been added to your project. These assemblies contain the classes that will be used by your game.

If you look at the Game1 class definition, you will see that it is derived from the “Microsoft.Xna.Framework.Game” class which comes from the “Microsoft.Xna.Framework.Game.dll” .NET assembly.

    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {

The Game class defines a few properties and methods that you will override in your your own game class to implement the logic of your game. The methods you will override will be explained next.

The Constructor

In the constructor of the Game class, a new GrapicsDeviceManager is created, passing this Game object as the only parameter.

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

The GrapicsDeviceManager is responsible for creating the GraphicsDevice object that is used to render graphics to the game screen.
After creating the GraphicsDeviceManager object, there are two ways to get access to the GraphicsDevice object. You can use the GrapichsDevice property of the Game class, or you can access the GraphicsDevice property of the GraphicsDeviceManager that was just created.

The Game class also creates a ContentManager object that is accessible via the Content property of the Game class. The ContentManager is used to load content into your game. In the constructor of the Game1 class, the base directory for game assets is specified. This folder is relative to the game’s executable file. In a later article, we will add some content to the Content project and use this content in-game.

The Initialize Method

In your own derived Game class, you will override the Initialize method. This method is used to create any GameComponent(s) or game services that will be used by your game. Game components and game services will be discussed in more detail in a later article.

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

By default, no components or game services are added to the game.

You should not use the Initialize method to load game content. Game content (images, fonts, models) will be loaded in the LoadContent method described next.

The LoadContent Method

Another method that you will override from the Game class is the LoadContent method. The purpose of the LoadContent method is to load all the data that has been added to the Content project (or Content sub-project if you are using XNA Game Studio 3.1). Images, shaders, models, fonts, are assets that you want to load into your game in this method. By default, there is no content to load but in a later article, we will load fonts and images in this method.

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
        }

The default template also creates an instance of a SpriteBatch object, but it is not used anywhere else in the template.

The UnloadContent Method

The UnloadContent method is used to unload graphics content from the game. Content that was loaded using the ContentManager does not need to be explicitly unloaded because it will be unloaded automatically. Only content that was loaded directly from disc (for example, content that is not recognized by the content importer) needs to be unloaded in this method.

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

Obviously since no content has been loaded, no content needs to be unloaded.

The Update Method

The Update method is responsible for updating all of the game logic. Here you will handle user input, update the position and orientation of game objects (including the camera), do collision detection for your physics simulation and possibly add and remove game components from your game’s component collection.

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        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);
        }

By default, the game only checks if the back button has been pressed on the first game pad connected to the PC. If so, the game will exit. If you also want to be able to exit the game by pressing the Escape key on your keyboard, we can modify this method to also check if the escape character is pressed.

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
                Keyboard.GetState().IsKeyDown(Keys.Escape) )
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

On line 71, I’ve added an extra condition that checks to see if the escape key has been pressed on the keyboard. Adding this line will allow you to exit the game if either the back button on the game pad is pressed, or the escape key on the keyboard is pressed.

The Draw Method

The final method that you will want to override is the Draw method. In the draw method, you will render all of the game objects to the screen. Rendering of drawable objects will be covered in a later tutorial.

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }

The default template simply clears the screen to cornflower blue using the GraphicsDevice object.

Conclusion

The objective of this brief tutorial is to introduce you to the XNA framework and get you started by creating a new Game project.

In later tutorials, I will explore loading images and fonts and creating a very basic 2D game.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.