XNA Development - A 2D Game Starter - part 1

Basic Game


For the first project, we'll shoot for something simple. We'll get a space ship onscreen that responds to player input. Open XNA Game Studio Express and click File -> New Project. Select 'Windows Game' and give it a name. If you hit F5 to start debugging, you'll get a blue window that doesn't (seem to) do much.

Ship Graqphic



This is our ship graphic.
It's a transparent PNG made in the GiMP.

First up, save the image in the content folder of your project. For my project that ends up being:
     ~\Visual Studio 2005\Projects\XNA2DStarter\XNA2DStarter\Content\ship.png


Now to get it to show up in Visual Studio...
In the Solution Explorer, right click on the content folder and select: Add -> Existing Item
Double click on ship.png and it should now show up in the Solution Explorer under the Content folder.

Next up we need to load it into the game so we can display it onscreen.

Declare a Texture2D in the Game1.cs code under the spriteBatch declaration:

...
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D shipTex;

public Game1()
...

Using the type Texture2D means we don't really care what type of image it is, just as long as it can be loaded.

Next in the LoadContent function, load the image into the variable we just created.

...
// 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
shipTex = Content.Load<Texture2D>("ship");
...

This code loads the content named "ship" into the variable shipTex. If you right-click on ship.png in the Solution Explorer and select properties, you can change it's name in 'Asset Name' Since it's a texture, we use the type Texture2D when calling Content.Load

Last up is actually drawing it. The SpriteBatch will do the drawing for us, we just tell it to start drawing, draw the texture, then stop drawing. In the Draw function add the following:

...
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(shipTex, new Vector2(10, 10), Color.White);
spriteBatch.End();

base.Draw(gameTime);
...



We call the Draw method, passing the texture, the upper left position (10 x 10), and a tint color (Color.White == no tint).
The ship should now show up in the upper left hand corner.

The very complicated solution.



<< Next >>