Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... ·...

17
Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed, we are ready to start making our game. Luckily, someone at Microsoft was thinking, and they made a pretty nice template for us to use to get started with our game. In this tutorial, we will look at how to create a new game using this template. After running our game for the first time, we will go back and take a look at the code in the template so that we understand what was created. Using the Template Using the template is fairly easy. When XNA Game Studio is opened, the Start Page will come up by default. Look in the upper left corner for a small link that says New Project… and push it. This will open up the New Project dialog. In this dialog, we will do three things to get our project started. First, in the Installed Templateslist, choose the XNA Game Studio 4.0 group. Second, in the list in the middle, choose the Windows Game (4.0). Finally, at the bottom of the dialog, give your project a name, as shown in the image below.

Transcript of Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... ·...

Page 1: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

Creating an XNA Game from the Template

Introduction

Now that XNA Game Studio is installed, we are ready to start making our game. Luckily, someone at

Microsoft was thinking, and they made a pretty nice template for us to use to get started with our game. In this

tutorial, we will look at how to create a new game using this template. After running our game for the first

time, we will go back and take a look at the code in the template so that we understand what was created.

Using the Template

Using the template is fairly easy. When XNA Game Studio is opened, the Start Page will come up by default.

Look in the upper left corner for a small link that says New Project… and push it.

This will open up the New Project dialog. In this dialog, we will do three things to get our project started.

First, in the Installed Templateslist, choose the XNA Game Studio 4.0 group. Second, in the list in the

middle, choose the Windows Game (4.0). Finally, at the bottom of the dialog, give your project a name, as

shown in the image below.

Page 2: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

When you are done with these things, click the OK button to tell Visual Studio to build your project. After a

moment, your project will appear on the screen, with the main game file opened for you to begin editing.

Running the Game

The nicest thing about the template is that the game is ready to run right away. You don't have to do anything

else. So let's go ahead and run our game for the first time. To do this, go to the Debug menu and choose

either Start Debugging or Start Without Debugging. Notice that they both have keyboard shortcuts (F5 and

Ctrl+F5), which might be worth remembering, since you will be performing this command a lot.

Page 3: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

After Visual Studio compiles your program, the game will start running and you should see the game appear.

If it doesn't work, and you see an error message that says something along the lines of "No suitable graphics

card found. Could not find a Direct3D device that supports the XNA framework HiDef profile…" then jump

down to the Handling the HiDef Profile Error section below, and come back when you've made the needed

changes.

When the game runs, it should look like the window below:

Page 4: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

The game comes up as a window, filled with a blue background. At this point, it doesn't really do anything, but

this takes care of a lot of work that we would have to do ourselves if we weren't using XNA.

At this point, you might be wondering why the background is blue. More specifically, the color is cornflower

blue. For starters, you need to pick some color to clear the screen with. But why cornflower blue? Why not

black or white? There is actually a fairly good reason for this.

Allow me to share a personal experience to help explain. Several years ago, I was starting to make a game. At

this point, I was only trying to draw a simple 3D model on the screen. However, the model wasn't being drawn.

I was really confused for a very long time. Finally, after a while, I realized that the model was actually being

drawn, but I had forgotten to turn on the lights in the game. So the entire model was black, and the background

was black.

Black backgrounds can make it difficult to see what is going wrong. The same thing is true for white. So they

pick a default color that isn't likely to cause problems, like cornflower blue. So why not red, green, or Papaya

Whip? Well, at this point, it is kind of an arbitrary decision. Some say that this color is a reference to the movie

Fight Club, but the XNA developers claim that it is just a color they liked.

Handling the HiDef Profile Error (HiDef Profile vs. Reach Profile)

On lots of computers, you may get an error that says the following:

Page 5: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

No suitable graphics card found.

Could not find a Direct3D device that supports the XNA Framework HiDef profile.

Verify that a suitable graphics device is installed.

Make sure the desktop is not locked, and that no other application is running in full screen mode.

Avoid running under Remote Desktop or as a Windows service.

Check the display properties to make sure hardware acceleration is set to Full.

One way to fix this is to follow the instructions on the error message. There may be some sort of setting that

you can change that will fix this problem. But for many people, that's not the issue.

Another choice that seems to work for everybody is to change from the HiDef profile to the Reach profile.

XNA has two different profiles. The HiDef profile allows you to access all of the most powerful functions,

while the Reach profile limits you, but allows you to "reach" more platforms, like the Windows 7 Phone. By

the way, the Reach profile seems to be enough for everything on this site, so you don't really have anything to

worry about with switching over to the Reach profile.

To make the switch, go over to the Project Explorer, and right-click on your project ("WindowsGame1" if

you didn't change the default name) and click on Properties in the context menu. This will open up the project

properties in a new window. On the left side, make sure that theXNA Game Studio tab is selected. On that

page, you'll see "Game profile:" with two options, one to use Reach, and one to use HiDef. Choose the Reach

option, and re-run your program. It should work now!

Understanding the Generated Code

Well now that we've seen our game running, let's go back and take a look at the code that was generated for us

from the template. For starters, if you look on the right side of the screen, you will see the Solution Explorer.

This shows us what files and stuff are included in our game. You will see here that in our program, there are

two source code files, Program.cs and Game1.cs (along with a few other items).Program.cs is just the entry

point to the application, which just creates a new instance of our game and runs it. You can double-click on the

file in the Solution Explorer to see the file, but you will probably not need to modify this file at all.

The Game1.cs file is more interesting. We will look at each of the parts of this file in turn, below.

Using Directives

Page 6: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

The first several lines of code are all using directives. These tell the compiler that we want to use various pre-

existing components that have been made elsewhere.

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;

Class Declaration and Instance Variables

The next section is where we define our class and create instance variables that belong to our game.

public class Game1 : Microsoft.Xna.Framework.Game

{

GraphicsDeviceManager graphics;

SpriteBatch spriteBatch;

You can see that our game class is called Game1. Eventually, you will probably want to rename this to

something else, which can be easily done by right clicking on the text and choosing Refactor > Rename.

Renaming the class this way will tell Visual Studio to go through all of our code and find any places where our

class is used and rename it there as well.

You'll also notice that our class extends the XNA Game class. This means that our game has all of the

properties and abilities of any XNA Game.

The template gives us two instance variables: graphics, which is what we use to do our drawing with,

and spriteBatch, which handles 2D rendering. We will use both of these in depth later on.

The Constructor

public Game1()

{

graphics = new GraphicsDeviceManager(this);

Content.RootDirectory = "Content";

}

The constructor is where the game gets set up. It is pretty simple, right now, and only needs to prepare our

instance variables to be used later.

The Initialize() Method

Page 7: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

protected override void Initialize()

{

// TODO: Add your initialization logic here

base.Initialize();

}

This is the method where we can do initialization of non-graphics related components of our game, such as

services.

The LoadContent() and UnloadContent() Methods

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

}

protected override void UnloadContent()

{

// TODO: Unload any non ContentManager content here

}

These two methods are where we will load all of our graphics related content, such as 3D models, background

images, and fonts. We will talk about this more later, in the Managing Content tutorial.

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);

}

This method is an important part of the game. This is where we update our game state. For example, this is

where we should check to see if a player is pushing a button, and respond accordingly.

The Draw() Method

protected override void Draw(GameTime gameTime)

{

GraphicsDevice.Clear(Color.CornflowerBlue);

Page 8: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

// TODO: Add your drawing code here

base.Draw(gameTime);

}

This is where you do all of your drawing. This, too, is an important method. Notice that

the Update() and Draw() methods have intentionally been separated. This is done on purpose, and it is a good

idea to follow this pattern. Try to keep drawing stuff out of the Update() method, and don't put anything in

the Draw() method that doesn't directly pertain to drawing.

Also, notice that this is where the background is filled in with the color cornflower blue. It is easy to change

that to something else here. TheColor class has a lot of colors to choose from, and you are also able to define

your own colors as well.

What's Next?

Managing Content in XNA

Introduction

One of the most powerful features of XNA is how well it handles content. Game content, also called art assets,

or just assets for short, is any sort of external data that is used in your game, aside from your code. Content

includes 3D models, textures for the models, shaders, 2D images, fonts, and even audio. XNA makes it easy to

manage your game's content. In this tutorial we will take a look at the basics of working with your game

content, so that we can use it in future tutorials.

The Content Manager & The Content Pipeline

In this tutorial, we are not going to go into great detail about how XNA handles your content, other than to say

that it does it in an easy, powerful, and extensible way. There are other tutorials that discuss how the Content

Pipeline works as well as how to extend it that you can look at later. For now, we will just state that all of your

content goes through a component that is called the Content Pipeline when you create it. The Content Pipeline

already knows exactly what to do with a very large set of file types, as shown below:

Content Type File Types

3D Models .x, .fbx

Textures/Images .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, .tga

Page 9: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

Audio .xap (an XACT audio project), .wma, .mp3, .wav

Fonts .spritefont

Effects .fx

Of course, later, we will get an opportunity to talk about each of these in more detail, so for now, you don't

need to worry about it too much. Additionally, you can create an extension to the Content Pipeline to include

even more file types too.

In our game, we have an instance of a ContentManager class that we can use to easily load an object from the

content pipeline, and as we'll see in a minute, it is pretty easy to do.

Adding Content to your Game

The first thing we need to do is to actually tell our game what content we want to include. To do this, go to the

Solution Explorer window on the right side of the screen. At the very top is your game's solution, labeled

"Solution 'CoolGame'" or whatever you called your game. Inside of that, you should see two projects, one

called "CoolGame" or whatever you called your game, and one called "CoolGameContent (Content)". The first

project is where all of our code will go, and the second one is where our content will be placed.

Page 10: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

This node actually represents a folder in the project directory called CoolGameContent, which is where your

content files will be stored. To add content to your game, right-click on the content project node and

choose Add > Existing Item from the popup menu. This will open up a file dialog that you can use to browse

your computer for the content you want in your game.

Go ahead and try it out now. Find an image file (or something else) on your computer and add it to your game.

The object will now appear under your content project node, as shown in the image below.

Using Folders to Organize Content

It is always a good idea to keep your content organized. When you have a small game, this isn't as important,

but as you begin to develop bigger games, this is really useful. You can organize your content by adding

directories to the content project node of your game by right clicking on the content project node, and then

choosing Add > New Folder.

The thing to keep in mind is that if the file you want appears somewhere under the content project node of your

game, it will be available during your game. If it isn't there, you won't be able to access it, and your game will

throw an exception and crash when you try to load it.

Loading Content in your Game

Page 11: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

OK, now we are on to the real interesting part. We are now going to use the content we just added. In other

tutorials, as we talk about using each of the different kinds of content in turn, we will discuss this in greater

detail. For now, though, we will just do something simple. Loading content in your game is always done in

about the same way. Go to your LoadContent() method in your game, and add the following line (replacing

"FullLogo" with the name of your file in quotes):

Texture2D image = Content.Load<Texture2D>("FullLogo");

A Texture2D object is simply a way of storing a picture. A texture is the computer graphics term for an image

that you place on a 3D object, which is one of the most common ways of using an image. There are other ways

to use a Texture2D object, as well. We will talk a little more about this in other tutorials. All we really need to

do to load our content is call the function Content.Load(), with the name of the asset that we want to load. In

the angle brackets ("<" and ">") we put the type of content that we are loading, which in this case, is simply

a Texture2D as well.

You do not need to put the extension on the file! In fact, you can't. It won't work if you do. This goes back to

earlier in the tutorial when we talked about how the Content Pipeline processes the file.

Also, if you have put your assets in different directories, you will need to put the path to the asset as well. For

example, if our image was in a directory called Backgrounds, we would need to say:

Texture2D image = Content.Load<Texture2D>("Backgrounds/FullLogo");

Unloading Content in your Game

For a small game, you may not ever need to unload any content in your game. However, if you have a big

game, you can't just keep loading more and more content and expect it to keep working. It is a good idea to

unload unnecessary content whenever you are done using it. So, for instance, you can unload all of the content

for a particular level, after the level is completed, so that there is room for the next level's content to be loaded.

To do this, simply add the following line to your program:

Content.Unload();

This frees up (almost) all of the content that was loaded by your content manager. Of course, this means that if

you want to reuse something that was previously loaded, you will need to load it again.

It might be a good idea to create multiple ContentManager objects to divide up the content. That way you can

call Unload() for theContentManagers that you are done with.

Even if you don't have a big game, it is still doesn't hurt to unload unused content.

Page 12: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

What's Next?

We've discussed how you can load content or art assets in your XNA game. This will make it easy to start

working on your game. There are a number of good things to do next, and you can pick whatever you want.

You might want to check out the tutorial about how the Content Pipeline works, if you are interested in

learning more about it. I think I would recommend going and looking at the tutorials on 2D graphics next, if

you haven't already done it. But, maybe you are just ready to start working on a 3D game. If so, you should

take a look at the tutorials on 3D graphics that are on this website.

ntroduction To 2D Graphics

Overview

In the next few tutorials, we will be taking a look at 2D graphics. 2D graphics can be very useful in game

programming. In addition to the fact that we can make games that are completely 2D, knowing how to do 2D

graphics can add a great deal to 3D games with very little effort. 2D graphics are used for splash screens,

menus, and HUDs (Heads-up Displays), among other things. In future tutorials, we will take a look at how to

actually do 2D graphics. In this tutorial, we will look at how to get started with 2D.

The 2D World

The 2D coordinate system that we are going to be using is a little different from the 3D system that we have

been using. The major difference (in addition to the obvious fact that there are only two dimensions) is that in

our 2D world, all of our coordinates will be based on pixels on the screen, rather than a world coordinate

system.

The important thing to remember here is that our system is not relative, because it is based on pixels. If we

want to draw something half way across the screen, we will have to calculate what half way is, based on our

window size. We will need to keep in mind the window size when we are drawing.

The 2D coordinate system’s origin is in the top left corner of the screen. The x-axis starts at 0 there, and goes

right. The y-axis starts there as well, and goes down. This is probably not very natural for you guys who have

not yet done very much with computer graphics, or have spent a lot of time doing math, because normally, the

y-axis would go up instead of down. However, this is the way it has always been done with 2D graphics, and

so we’re not about to change it right now.

Page 13: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

Sprites

No, this section is not about ghosts, and it is not about elves. And it is also not about lemon-lime flavored

beverages either. In computer graphics, a sprite is a two-dimensional image. Nearly everything we do while we

are doing 2D graphics will be a sprite, since most of our work will involve drawing 2D images on the screen in

the spots we want them.

Of course, the definition of sprites isn’t just limited to 2D drawing. Sprites even come up in a 3D world. They

are often used to achieve fancy effects, like explosions (point sprites), fire, and smoke. They can also be used

in simple ways to get detailed images of objects without having to create a complicated 3D model (bill

boarding and cross bill boarding). For example, we could use a picture (sprite) of a missile, rather than creating

(and spend all of that energy rendering) a detailed 3D model. For the time being, we will be looking at sprites

in a 2D world, and later on we can come back and discuss how to use sprites in a 3D game.

SpriteBatch Basics

Overview

In this tutorial, we will take a look at the core feature of 2D drawing: the SpriteBatch class. The SpriteBatch

class can do lots of things. This tutorial will not cover everything that the SpriteBatch class can do, but just get

us going with it. During this tutorial, we will learn how to draw sprites on the screen.

For this tutorial, we will assume that you are starting with a brand new project, but it is pretty easy to add this

code into an existing project that you are already working on.

Preparing the Content

Page 14: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

The first thing we will need to do to is make sure we have some sprites to draw. We are going to add some

images to our project in the same way that we've done in other tutorials. So for starters, let's get some images.

You can get your own images from anywhere you want. I've posted a few images on this website, located

at http://rbwhitaker.wikidot.com/spritebatch-basics-resources which I will use in this tutorial, and you are free

to use as well. Take the images you want and add them to your project like we've done before. (Right click on

your content project in the Solution Explorer and click on Add > Existing Item, and then browse and choose

your files.) Try to have a couple of different images so that we can play around with them.

Create a Place to Store the Images In Game

Now we need to load the images in to Texture2D objects. Let's create a few Texture2D objects to store our

images. Add the following three lines of code as instance variables to our game's main class:

private Texture2D background;

private Texture2D shuttle;

private Texture2D earth;

Loading the Images

Now let's actually load the images into our texture objects. In the LoadContent() method, add the following

lines of code:

background = Content.Load<Texture2D>("stars"); // change these names to the

names of your images

shuttle = Content.Load<Texture2D>("shuttle"); // if you are using your own

images.

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

Now our images are loaded into our game and are ready to be drawn.

SpriteBatches

SpriteBatches are the most important (arguably the only important) component of 2D drawing. A SpriteBatch

contains methods for drawing groups of sprites onto the screen.

We will first need a SpriteBatch object to do drawing. The standard template already has added

a SpriteBatch object to our game for us to use, and the Microsoft people were nice enough to get it set up for

us. If you look just inside your game's class at the instance variables, you will see one that looks like the line

below:

SpriteBatch spriteBatch;

Page 15: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

You will also see a reference to this SpriteBatch class in the LoadContent() method, where the SpriteBatch

object is assigned a value.

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

}

Drawing with SpriteBatches

All that is left for us to do is the actual drawing of our sprites.

As a first step to drawing, let's draw the background. A SpriteBatch is used to draw a whole bunch of sprites

all at one time. It is much more efficient this way, rather than drawing each sprite individually. To draw with

a SpriteBatch, we will first indicate that we want to begin using our SpriteBatch to draw a "batch" or group of

sprites. We will then draw our sprites, and when we're done, we will indicate that we are done drawing our

batch of sprites. Go down to the Draw() method and add the following three lines of code:

spriteBatch.Begin();

spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.White);

spriteBatch.End();

We already mentioned what spriteBatch.Begin() and spriteBatch.End() do. Let's take another look at the

spriteBatch.Draw() call. The first argument says what texture we want to use. We are using our background

texture. The second argument is a Rectangle that indicates where the sprite should be drawn. The first two

parameters of the Rectangle constructor are the x and y-coordinates respectively, and the third and fourth are

the width and height. This will fill up the entire window, since it is 800 x 480 by default. (This is the resolution

of most Windows 7 Phones, by the way.) The last parameter for the Draw() command is a tint color. We don't

want our image tinted at all, so we use Color.White.

You can try playing around with different tint colors to see what it does.

At this point we can run our game and see what it looks like. If you are using the same images as me, it should

look like the screen shot below:

Page 16: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

A Few More Sprites

We've essentially done the basics of SpriteBatches. But before we stop, let's draw a couple more sprites with a

couple of other methods. Let's add the following two lines of code to the Draw() method, just after our

previous spriteBatch.Draw() call, and before the spriteBatch.End() call.

spriteBatch.Draw(earth, new Vector2(400, 240), Color.White);

spriteBatch.Draw(shuttle, new Vector2(450, 240), Color.White);

This will make our Draw() method look like this:

protected override void Draw(GameTime gameTime)

{

graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

spriteBatch.Begin();

spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.White);

Page 17: Creating an XNA Game from the Templateschoolwires.henry.k12.ga.us/cms/lib08/GA01000549... · Creating an XNA Game from the Template Introduction Now that XNA Game Studio is installed,

spriteBatch.Draw(earth, new Vector2(400, 240), Color.White);

spriteBatch.Draw(shuttle, new Vector2(450, 240), Color.White);

spriteBatch.End();

base.Draw(gameTime);

}

These two lines of code that we added use a slightly different version of the SpriteBatch.Draw() method. With

this version, the first parameter is the texture, like before, and the last parameter is the tint color like before,

but the middle parameter is a Vector2 instead of a Rectangle. This is the location that the sprite will be drawn

on the screen. We've put the earth sprite at (400, 240), which is the center of the screen (at least, the upper left

corner of the Earth texture is) and the shuttle texture just a little bit more to the right of that.

The order that you draw sprites is important. Whatever you draw first will be drawn below the later things. It is

kind of like stacking them up. We can now run our game and see the new textures.