"Hello World!" in XNA
In the last post I made, we saw how to create a XNA game project and run it. It didn’t do anything fancy at all, just a blue screen. Now let’s take it further and explain the code that is generated by the project template and extend it to display a nice “Hello World” text on the screen. Baby steps everyone, baby steps!
Before you proceed reading how the code works, it might be good to take a moment and read the first part of the “Anatomy of a Game” series I posted here. It is very relevant to what we’ll talk about now.
So you just created your super cool XNA game project and ran it. Got the nice blue screen and all that good stuff. So what does the code look like? Looking at Solution Explorer in Visual Studio, we see the following:
Let’s see what we have here. First thing you’ll notice (or may not notice, it’s kind of subtle) is that we have two projects in here. We have the HelloWorld project, and we have the nested Content project. The main difference is that the parent HelloWorld project is where your code will live, and the nested or child Content project is where your game assets will go. By game assets I mean the graphics, audio, etc. You won’t be putting code in the Content project. Don’t worry too much about the details of the content project now, we’ll get into this later.
Taking a closer look at the files in the HelloWorld project, we have:
Game.ico: That’s the icon that will be used for the final .exe that gets built. Nothing new here from Windows applications and all that stuff.
Game1.cs: This is the main game code C# file. We will be spending a lot of time here.
GameThumbnail.png: This is the thumbnail image that the game will use whenever it’s asked for a Thumbnail. So things like the game’s Icon in Xbox 360’s dashboard for instance will use this. Make it pretty!
Program.cs: This is the main program entry. Nothing really exciting in here. Just the Main function spinning up the game. You won’t be messing with this file as much.
Show me the code!
Ok! Let’s have a look at the code! Open up Game1.cs and skim through it. The general layout of the file looks like this (I removed the actual code blocks for readability):
1: public class Game1 : Microsoft.Xna.Framework.Game
2: {
3: GraphicsDeviceManager graphics;
4: SpriteBatch spriteBatch;
5:
6: public Game1()
7:
8: protected override void Initialize()
9:
10: protected override void LoadContent()
11:
12: protected override void UnloadContent()
13:
14: protected override void Update(GameTime gameTime)
15:
16: protected override void Draw(GameTime gameTime)
17: }
Looks familiar? It should. It follows the flow I pointed out in the first part of the “Anatomy of a Game”:
The template first declares two member variables (lines 3 & 4):
- GraphicsDeviceManager
- SpriteBatch
The GraphicsDeviceManager is the class that manages your GraphicsDevice. Your GraphicsDevice is the device that you use to draw to the screen. It is an abstracted representation of the graphics card if you will. You use it to talk to the graphics card and tell it what to draw. You will become very intimate with the GraphicsDevice. Learn to love it!
SpriteBatch is a class in the Framework that you can use to draw sprites (images) on the screen as well as writing text. Another class you will learn to use quite a bit. If you’re going to write a 2D game, you will use this all the time. Even in a 3D game, you’ll still need to draw 2D elements like the HUD (score, weapons, ammo, health indicators,etc). Again, learn to love it.
Initialize (line 8): This method gets called when your game is first loaded. So you will want to put code in here that will only run once in the lifetime of the game. Initializing arrays, lists, etc.
LoadContent (line 10): This is where you want to have your content get loaded. So if you have some 3D models, sprites, etc in your game, you load them here.
UnloadContent (line 12): The game will call this function when it needs to unload your content from memory. You won’t be messing with this function for a while. The defaults in there work fine.
Update (line 14): This method gets called by the Game runtime at specific intervals. This way you know that the time between each call to this function is the same regardless of how fast the machine running your game is. This is where you will put code to process the actual game, move stuff around, calculate collisions, update user interface data, etc.
Draw (line 16): This method gets called by the framework everytime it wants you to draw to the screen. You will add code here to do all the rendering for your game.
Simple eh? Not too complicated once you break it down. To really understand how all this works together, how about we display some text!
“Hello World”: The Making
Alright, let’s build our first real “Hello World”.
The “game” will simply draw some text on the screen and that’s it. Nice and simple yet will cover all the basics.
To draw text on the screen, you will want to add a SpriteFont description file to your project. What that does is let you describe what the font will look like. To add the sprite font description file, you add it in the Content folder:
Right click on the Content node and select Add->New Item as in the image above.
Click on “Sprite Font” in the “Add New Item - Content” dialog that appears:
This will add a new file to your Content project called “SpriteFont1.spritefont”:
Double click on the file and let’s edit it. The file is in XML, so it’s easy to edit. You want to change the value of the FontName element to be a valid font in your system, I picked Arial. I also set the size of the font to 24 by editing the Size element in the XML file. Save the file before you forget.
Now open up Game1.cs and let’s use our font to draw some text on the screen.
First you need to add a new member variable of type SpriteFont like this (line 3):
1: GraphicsDeviceManager graphics;
2: SpriteBatch spriteBatch;
3: SpriteFont font;
Now we need to load the sprite font we defined into that instance of SpriteFont. Where do we load content? In the LoadContent method of course:
1: protected override void LoadContent()
2: {
3: // Create a new SpriteBatch, which can be used to draw textures.
4: spriteBatch = new SpriteBatch(GraphicsDevice);
5:
6: // load our font
7: font = Content.Load<SpriteFont>(“spritefont1″);
8: }
Looking at line 7, you’ll see how you can load any piece of content using the Content Pipeline. We tell it to load an asset that is of type SpriteFont and the name of that asset is “spritefont1″. Voila! The font object is now loaded and ready to be used!
Note: Notice how we didn’t use the full file name as the name of the asset to load. We did not specify the .spirtefont extension. This is one of the first rookie mistakes most people do. From now on, any content you load, you never specify the extension in the content.load method. You’ll get an error otherwise.
Ok! Now we have our font, what do we want to do next? Draw some text on the screen with it. Drawing happens in the Draw function of course. To draw a font, we use the SpriteBatch object to do all the drawing:
1: protected override void Draw(GameTime gameTime)
2: {
3: graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
4:
5: spriteBatch.Begin();
6: spriteBatch.DrawString(font, “Hello World”, new Vector2(30, 30), Color.Black);
7: spriteBatch.End();
8:
9: base.Draw(gameTime);
10: }
First thing we do in the Draw method is clear the screen by calling GraphicsDevice.Clear method (line 3). We tell our device to clear the contents of the screen and replace it all with the color CornFlowerBlue. This is done every frame to remove clear the “slate” and start over fresh for this frame.
SpriteBatch works by first calling the Begin method, then adding the calls to drawing and then closing it with the End method. We use the DrawString method as shown in line 6 to Draw the string “Hello World” at position (x,y) = (30,30) and use Color.Black.
Finally we pass control to base.Draw so that the framework would continue whatever it needs to do to actually display what we render!
That’s it! Hit F5 to run the program and you’ll see the following game:
There you have it! Your first actual game showing some awesome “Hello World” text. Next post we’ll learn how to use the Update function to move this text around a bit and do some interesting stuff with it.
Have fun!
Thanks for reading! I'd love to hear your thoughts, feel free to leave a comment below. Don't forget to subscribe to my RSS Feed!
December 4th, 2007 at 3:39 pm
Hello World in XNA…
Nazeeh has posted a really good article that goes through a good introduction to the base game project…
December 4th, 2007 at 4:23 pm
Hello World in XNA [Mykres Space]…
Nazeeh has posted a really good article that goes through a good introduction to the base game project…
October 23rd, 2008 at 6:28 am
good tutoring, i will use to start developing in xna, thanks alot for it