Your First Game: Microsoft XNA Game Studio Express in 2D
This article leads you through the steps necessary to create a simple sprite-based game by using XNA Game Studio Express.
- Step 1: Install Your Software
- Step 2: Create a New Project
- Step 3: View the Code
- Step 4: Add a Sprite
- Step 5: Make the Sprite Move and Bounce
- Step 6: Explore!
- The Complete Example (contents of Game1.cs)
Step 1: Install Your Software
Before you begin, make sure that you have installed all the necessary software, including Visual C# 2005 Express Edition and XNA Game Studio Express. See Required Software for a list of required programs.
Step 2: Create a New Project
From the Start Menu, click All Programs, then the Microsoft XNA Game Studio Express folder, and finally XNA Game Studio Express.
When the Start Page appears, click the File menu, and then click New Project.
In the dialog box that appears, choose Windows Game and type a title for your project (such as "MyFirstXNAGame") in the Name box. Type a path where you'd like to save your project in the Location box. Then click OK.
After creating a new project, you'll be presented with the code view of your game.
Step 3: View the Code
Some of the hard work has already been done for you. If you build and run your game now, the GraphicsDeviceManager will handle setting up your screen size and rendering a blank screen. Your game will run and update all by itself. It's up to you to insert your own code to make the game more interesting.
Much of the code to start and run your game has already been written for you, and all have places for you to insert your code.
- The Initialize method is where you can initialize any assets that do not require a GraphicsDevice to be initialized.
- The LoadGraphicsContent method is where you load any graphical assets such as models and textures.
- The UnloadGraphicsContent method is where any graphical assets can be released. Generally, no extra code is required here, as assets will be released automatically when they are no longer needed.
- The Update loop is the best place to update your game logic: move objects around, take player input, decide the outcome of collisions between objects, and so on.
- The Draw loop is the best place to render all of your objects and backgrounds on the screen.
Step 4: Add a Sprite
The next step is to add a graphic that can be drawn on the screen. Use a small graphics file, such as a small .bmp or .jpg file. Be creative—you can even make your own.
You can even skip ahead a bit and make a sprite that "hides" parts that shouldn't be seen (such as edges or corners) so that it looks even better. For an example, see How to: Make a Texture with Masking.
Once you have a graphic picked out on your computer, follow these steps.
Make sure you can see the Solution Explorer for your project on the right side of the window. If you cannot see it, click the View menu, and then click Solution Explorer. When it appears, you will see files associated with your project in a tree structure.
Right-click your project in Solution Explorer, click Add, and then click Existing Item. Browse to your graphic. If you can't see any files, make sure you change the Files of type selection box to read Content Pipeline Files. Click the graphic file, then click Add. An entry for the graphic file will appear in Solution Explorer.
When you add a graphic file, it is automatically added to the XNA Framework Content Pipeline, which will allow you to quickly and easily load the graphic in your game.
Click the entry for the graphic in the Solution Explorer. In the Properties window below Solution Explorer, look for the "Asset Name" property. Note the name; you'll use it in your code to load the graphic so it can be displayed in your game. If the Properties window isn't visible, press F4, or click the View menu, and then click Properties Window.
Now, you must write code that loads and displays the sprite on the screen. You can use the instructions in How to: Draw a Sprite, or follow along here.
Back in the Code view of your game, find the LoadGraphicsContent method, and add the following lines in and above the method so it looks similar to this:
// This is a texture we can render. Texture2D myTexture; // Set the coordinates to draw the sprite at. Vector2 spritePosition = Vector2.Zero; // This is the object that will draw the sprites. SpriteBatch spriteBatch; protected override void LoadGraphicsContent( bool loadAllContent ) { if (loadAllContent) { myTexture = content.Load<Texture2D>( "mytexture" ); spriteBatch = new SpriteBatch( graphics.GraphicsDevice ); } }
Make sure the call to ContentManager.Load is using the "Asset Name" you saw in the Properties window in the previous step. This code will load and prepare your graphic to be drawn, and will reload your graphic if the graphics device is reset (such as in the case of the game window being resized).
Now, add code to the Draw loop so it looks like this:
protected override void Draw( GameTime gameTime ) { graphics.GraphicsDevice.Clear( Color.CornflowerBlue ); // Draw the sprite. spriteBatch.Begin( SpriteBlendMode.AlphaBlend ); spriteBatch.Draw( myTexture, spritePosition, Color.White ); spriteBatch.End(); base.Draw( gameTime ); }
This code draws the sprite on the screen each frame.
Build and run your game. The sprite appears. Now, it's time to give it some motion.
Step 5: Make the Sprite Move and Bounce
Change the lines of code in and above the Update method to read this way:
// Store some information about the sprite's motion. Vector2 spriteSpeed = new Vector2( 50.0f, 50.0f ); protected override void Update( GameTime gameTime ) { // Allows the default game to exit on Xbox 360 and Windows. if (GamePad.GetState( PlayerIndex.One ).Buttons.Back == ButtonState.Pressed) this.Exit(); // Move the sprite around. UpdateSprite( gameTime ); base.Update( gameTime ); } void UpdateSprite( GameTime gameTime ) { // Move the sprite by speed, scaled by elapsed time. spritePosition += spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; int MaxX = graphics.GraphicsDevice.Viewport.Width - myTexture.Width; int MinX = 0; int MaxY = graphics.GraphicsDevice.Viewport.Height - myTexture.Height; int MinY = 0; // Check for bounce. if (spritePosition.X > MaxX) { spriteSpeed.X *= -1; spritePosition.X = MaxX; } else if (spritePosition.X < MinX) { spriteSpeed.X *= -1; spritePosition.X = MinX; } if (spritePosition.Y > MaxY) { spriteSpeed.Y *= -1; spritePosition.Y = MaxY; } else if (spritePosition.Y < MinY) { spriteSpeed.Y *= -1; spritePosition.Y = MinY; } }
This adds a little bit of logic that will move the sprite around each frame, and cause the sprite to change direction if it hits the edges of the game window.
Step 6: Explore!
From here, you can do just about anything. If you're ready to jump into a more complex example, including 3D graphics, input, and audio, see Going Beyond: XNA Game Studio Express in 3D.
Here are some more ideas to extend this sample.
- Experiment with the call to SpriteBatch.Draw. Change the Color parameter to tint the sprite. See How to: Tint a Sprite.
- Add a second sprite, and use BoundingBox objects to allow the sprites to collide with one another. (See How to: Detect Whether Two Models Collide.)
- Use Keyboard, Mouse, or GamePad to make the sprite respond to movements of an input device. (See Input Overview.)
- Create some audio events so that the sprite makes sounds as it moves. (See How to: Add a Sound File to Your Game Using XACT and How to: Play a Sound.)
- Instead of a sprite, use a 3D primitive that moves around in 3D space. (See How to: Draw Points, Lines, and Other 3D Primitives.)
The Complete Example (contents of Game1.cs)
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
ContentManager content;
public Game1()
{
graphics = new GraphicsDeviceManager( this );
content = new ContentManager( Services );
}
protected override void Initialize()
{
base.Initialize();
}
// This is a texture we can render.
Texture2D myTexture;
// Set the coordinates to draw the sprite at.
Vector2 spritePosition = Vector2.Zero;
// This is the object that will draw the sprites.
SpriteBatch spriteBatch;
protected override void LoadGraphicsContent( bool loadAllContent )
{
if (loadAllContent)
{
myTexture = content.Load<Texture2D>( "mytexture" );
spriteBatch = new SpriteBatch( graphics.GraphicsDevice );
}
}
protected override void UnloadGraphicsContent( bool unloadAllContent )
{
if (unloadAllContent == true)
{
content.Unload();
}
}
// Store some information about the sprite's motion.
Vector2 spriteSpeed = new Vector2( 50.0f, 50.0f );
protected override void Update( GameTime gameTime )
{
// Allows the default game to exit on Xbox 360 and Windows.
if (GamePad.GetState( PlayerIndex.One ).Buttons.Back == ButtonState.Pressed)
this.Exit();
// Move the sprite around.
UpdateSprite( gameTime );
base.Update( gameTime );
}
void UpdateSprite( GameTime gameTime )
{
// Move the sprite by speed, scaled by elapsed time.
spritePosition += spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
int MaxX = graphics.GraphicsDevice.Viewport.Width - myTexture.Width;
int MinX = 0;
int MaxY = graphics.GraphicsDevice.Viewport.Height - myTexture.Height;
int MinY = 0;
// Check for bounce.
if (spritePosition.X > MaxX)
{
spriteSpeed.X *= -1;
spritePosition.X = MaxX;
}
else if (spritePosition.X < MinX)
{
spriteSpeed.X *= -1;
spritePosition.X = MinX;
}
if (spritePosition.Y > MaxY)
{
spriteSpeed.Y *= -1;
spritePosition.Y = MaxY;
}
else if (spritePosition.Y < MinY)
{
spriteSpeed.Y *= -1;
spritePosition.Y = MinY;
}
}
protected override void Draw( GameTime gameTime )
{
graphics.GraphicsDevice.Clear( Color.CornflowerBlue );
// Draw the sprite.
spriteBatch.Begin( SpriteBlendMode.AlphaBlend );
spriteBatch.Draw( myTexture, spritePosition, Color.White );
spriteBatch.End();
base.Draw( gameTime );
}
}