Archive for the ‘Beginner Game Tutorials’ category

Animated Textures

December 10th, 2007

In my last post, we talked about textures in general and how to use them. This post will talk about a fun and important aspect of using textures in 2D games: Animation. Say you have a 2D game and you have Wizard character that the player controls and it can cast a spell. It would be boring if the wizard did not have any cool animation to indicate that he is casting a spell. This is where animation comes handy! We can use animation to make a 2D image appear to be alive and have motion.

So how do you create such an animation? First you need to have the actual animation designed. I found a free-to-use animated GIF on the web that I will use for this post:

Doing_magic

As you can see from the image, it’s a simple animation of a wizard using a wand. We want to take this wizard and use him in our game and have this animation be available.

So how do we do that? Every animation is made up of what’s called “Frames”. That means that the animation is actually a series of images each showing one step of the animation. For this one, you have the following 3 frames that make up the animation:

Doing_magic

It should be clear now how the animation works, right? It’s 3 frames that you display one after the other with a long enough delay in between to make it look good. So let’s see how we can get this animation to work in a game we build.

Create the animation into a horizontal strip

First thing you need to do is create the animation you want somehow. One way I tend to do it is by either finding animated gifs on the web that are “free” to use, or built them on my own. I can’t go into how to build them now since that’s outside the scope of this post. But basically, you need to build something like the second image up there. A horizontal strip that has all the frames of the image on it.

The image strip that contains your frames should have a correct size though! Every frame should be exactly the same width as the others. So if you have 3 frames in your strip, the width of the strip should be 3 x Width of one frame. You’ll see why later.

If you have an animated Gif like mine here, you can use this really cool tool I found on the web to convert it to a strip: Bitstrip.

Bitstrip is a simple tool that can convert animated GIF to a horizontal strip. To do that, fire up the tool, it has a very simple UI:

image

Click on “Browse to GIF file” button and find your GIF file.

Click on “Horizontal” button to see what the horizontal strip would look like.

With the Horizontal view open, click on “Save output as” and save the output file somewhere on your machine. It will be a .bmp file that looks like this:

image

What is all that pink???? Nothing to worry about! That’s the color the tool uses to indicate that this should be transparent. Fortunately, that is the same color that a lot of tools (and XNA Game Studio) use to indicate transparency. This technique is called Color Keying (you can read about more about it on Wikipedia).

Animating the texture in code

So now that we have the final texture we’ll use, it’s time to figure out how to animate it using code. Let’s examine what we’ll need to do:

  1. Need to figure out how many frames we have (nothing to figure out, we know from the image we created)
  2. Figure out the width of a single frame. Easy. Frame Width = Total Width of strip / number of frames.
  3. We need to render frame 1, then wait for sometime, then render frame 2, wait for sometime, etc until we reach the end of the frames. We can then loop back again to frame #1.

I happen to have a class that I wrote that specifically does what we listed just now. I call it: AnimatedTexture. Here’s the code:

 

   1: class AnimatedTexture
   2: {
   3:     private Texture2D aniTex;
   4:     private int CurrentFrame = 0;
   5:     private int numberOfFrames = 0;
   6:     private int msBetweenFrames = 0;
   7:
   8:     private Rectangle rect;
   9:
  10:     private int width = 0;
  11:     private int height = 0;
  12:
  13:     float timer = 0;
  14:
  15:     public AnimatedTexture(Texture2D texture, int numFrames, int msBetweenFrames)
  16:     {
  17:         this.aniTex = texture;
  18:         this.numberOfFrames = numFrames;
  19:         this.msBetweenFrames = msBetweenFrames;
  20:
  21:         this.width = texture.Width / numberOfFrames;
  22:         this.height = texture.Height;
  23:
  24:         // Init rectangle
  25:         rect.X = 0;
  26:         rect.Y = 0;
  27:         rect.Width = width;
  28:         rect.Height = height;
  29:     }
  30:
  31:     public void Update(GameTime gametime)
  32:     {
  33:         timer += gametime.ElapsedGameTime.Milliseconds;
  34:
  35:         if (timer >= msBetweenFrames)
  36:         {
  37:             timer = 0;
  38:
  39:             if (CurrentFrame++ == numberOfFrames - 1)
  40:                 CurrentFrame = 0;
  41:
  42:             rect.X = CurrentFrame * width;
  43:             rect.Y = 0;
  44:         }
  45:     }
  46:
  47:     public void Render(SpriteBatch sb, Vector2 position, Color color)
  48:     {
  49:         sb.Draw(aniTex, position, rect, color, 0, Vector2.Zero, 2.0f, SpriteEffects.None, 0);
  50:     }
  51:
  52: }

Let’s have a closer look at the code:

Lines 3-13: Local variables that we will use

Line 15: This is the constructor of the class. It takes the following arguments:

  • Texture2D texture: This is the strip we prepared. Load it up using the Content pipeline and pass it here.
  • int numFrames: This is the number of frames in the strip. User provided.
  • int msBetweenFrames: This is how many milliseconds should we wait between frames. The lower, the faster the animation.

Lines 21,22: Here we calculate the width and height of a single frame. Simple.

Lines 25-28: We initialize a rectangle to contain the first frame in the strip. We will use this in the rendering.

Lines 31-44: This is the Update method for the class. This method calculates the values in our Rectangle to move it to contain the next frame when it’s time. Time is calculated via the GameTime object so that we can tell when to move on to the next frame. We wait for a total number of msBetweenFrames milliseconds before moving on to the next frame. Simple math.

Lines 47-50: This is the Render method. Here we use a SpriteBatch object the user passes in along with a position and color to draw the current Rectangle from the texture. SpriteBatch has an overload that lets you specify a region in the texture to draw rather than the entire thing. This is why we’ve been calculating a rectangle for each frame in the Update method. We only draw the content of this rectangle each time.

Using the code in your game

Using the AnimatedTexture class we just created in our game is very easy.

Create a member variable in your Game1.cs file, in the Game1 class:

AnimatedTexture aniTex;

Load a texture in it in the LoadContentMethod:

 

   1: protected override void LoadContent()
   2: {
   3:     spriteBatch = new SpriteBatch(GraphicsDevice);
   4:     aniTex = new AnimatedTexture(Content.Load<Texture2D>("doing_magic"), 3, 80);
   5: }

I used 80 ms as the in-between frames delay. It seemed to look fine.

Make sure to call the Update method for the AnimatedTexture in the Update method:

 

   1: protected override void Update(GameTime gameTime)
   2: {
   3:     // Allows the game to exit
   4:     if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
   5:         this.Exit();
   6:
   7:     aniTex.Update(gameTime);
   8:
   9:     base.Update(gameTime);
  10: }

Finally, call the Render method in the Draw method:

 

   1: protected override void Draw(GameTime gameTime)
   2: {
   3:     graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
   4:
   5:     spriteBatch.Begin();
   6:     aniTex.Render(spriteBatch, Vector2.Zero, Color.White);
   7:     spriteBatch.End();
   8:
   9:     base.Draw(gameTime);
  10: }

There you go! It’s done :) Hit F5 and you should see a cool animation running. You can move it around by adding movement code just like you would for a normal texture. Just change the position argument in the Render method for AnimatedTexture.

Have fun!

Let’s Talk Textures!

December 6th, 2007

The subject of today’s topic is one that is quite interesting to me and something you will probably spend sometime playing around with. I want to talk about Textures, specifically Texture2D class in the framework. If we’re going to talk about Textures, then we will have to talk about SpriteBatch as well since that’s the class we use to draw textures on the screen.

First off, what is a texture? In its simplest form, a texture is an image. It is known by many different names that probably do have slightly different interpretations, but to me they are somewhat the same: Bitmap, Image, Picture, Sprite, etc. If you look at a game like Street Fighter 2 for instance, that is what is called a 2 Dimensional game (2D) and is completely made up of “Sprite graphics”. Which are…textures.

What do you use Textures for?

Well, the simplest example is in 2D games. All the graphics on the screen are images that you move around to simulate a world and gameplay. Just like in my previous post where we created an image of a ball and moved it around using the keyboard.

Textures are also used in 3D graphics all the time. The are used to cover the models with colors and detail to give that final polished look of a car or character. Things such as T-shirts and patterns on a model are textures. Terrain is another place where textures shine in 3D graphics. Things such as grass, rocks, etc that cover land in a game are textures.

Textures in their most basic form are really 2D arrays of numbers. A number at position X,Y that says the color for this pixel is Yellow for instance. So you end up seeing game developers using Textures as 2D arrays in their games. They store data in there that is not meant as a picture at all, will even look weird if rendered, but they instead read that data on the graphics card to achieve some interesting effects on the game. We’ll eventually see some of that stuff as we get more “seasoned’.

Creating Textures

So how do you create textures? It’s really pretty simple. You can create textures using any of the widely available image editing programs such as Photoshop, Gimp, Paint.Net and even the Microsoft Paint program that’s included in Windows by default. Anything that can save as one of the popular image types such as jpg, bmp, png, etc will work just fine.

You can also create images programmatically! You won’t use that very often in a 2D game, but you’ll find a few scenarios here and there that might present themselves.

Let’s Play with Textures!

Let’s fire up our Visual Studio and start getting familiar with Textures and what we can do with them. Create an new Windows Game project and start messing with textures!

Let’s start by giving our game a nice cool background or backdrop. The image I will use for my backdrop is one that is part of the SpaceWar starter kit that comes with XNA Game Studio. It looks like this:

image

You can use this one too if you want. Save it to your hard drive and add it to your project. Mine is already in my project:

image

Now we use it!

Have a variable declared for it:

Texture2D background;

Load it (line 5):

 

   1: protected override void LoadContent()
   2: {
   3:     // Create a new SpriteBatch, which can be used to draw textures.
   4:     spriteBatch = new SpriteBatch(GraphicsDevice);
   5:     background = Content.Load<Texture2D>("B1_nebula01");
   6: }

Render it (lines 5,6,7):

 

   1: protected override void Draw(GameTime gameTime)
   2: {
   3:     graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
   4:
   5:     spriteBatch.Begin();
   6:     spriteBatch.Draw(background, Vector2.Zero, Color.White);
   7:     spriteBatch.End();
   8:
   9:     base.Draw(gameTime);
  10: }

Tip: Did you notice the little trickery that is in line 6? I wanted to position the image at coordinates 0,0 of the game window. I could have said “new Vector2(0,0)”, but why would I do that when Vector2 class has a nice “.Zero” static method on it that returns a (0,0) Vector2. You’ll find a similar method on Vector3 and Vector4 as well.

Hit the magic F5 key and let’s have a look at the awesomeness we just created:

image

Oh! Come on!!! The image doesn’t fit the window size correctly. Now what? I can do one of 3 things:

  1. Resize the image in some image editor to make it fit
  2. Resize the Window to make that fit the image
  3. Scale the image in the Window to make it stretch out and fit any window size.

Alright, I’ll go with option #3 since it’s easy and will work with whatever size window we have from now on. So how do we do that? SpriteBatch.Draw method has a lot of overloads, so let’s see if it has something that can help. Sure enough, it has a method that can take a Rectangle that defines the destination area to draw the image in. This will work just fine! Here’s the code:

 

   1: protected override void Draw(GameTime gameTime)
   2: {
   3:     graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
   4:
   5:     Rectangle rect;
   6:     rect.X = 0;
   7:     rect.Y = 0;
   8:     rect.Width = graphics.GraphicsDevice.Viewport.Width;
   9:     rect.Height = graphics.GraphicsDevice.Viewport.Height;
  10:
  11:     spriteBatch.Begin();
  12:     spriteBatch.Draw(background, rect, Color.White);
  13:     spriteBatch.End();
  14:
  15:     base.Draw(gameTime);
  16: }

Alright, so what’s happening here?

Rectangle Struct defines a rectangle area by the X and Y coordinates on screen and a Width and Height to use. We already know that we want the image to start from (x,y) = (0,0) which is the top left corner of the screen. Now all we need to do is have it extend to the width and height of the screen and we’re golden. How do we get the Width and Height of the screen in XNA? check out lines 8 and 9. They use:

graphics.GraphicsDevice.Viewport

This class contains a lot of information regarding the details of the screen we’re drawing to right now on the graphics card. It has a Width and Height property on it which are exactly what we need. We set them on the Rectangle struct and use that in the Draw method of SpriteBatch instead of the Vector2.Zero part. Again, hit F5 and you should see:

image

Much nicer! Granted, the image is stretched out a bit and may not look good with other backdrops, but it looks fine with this one.

Taking it one step further

Ok, so now that we learned a bit more about textures and how we can resize them as we draw them, let’s learn about what we can do to mess with how they look a bit. And since now we know how to render textures on screen pretty easily, you can use my previous post to render the ball on top of this back drop since we’ll use it in the coming part.

So right now, my code that includes the ball looks like this:

 

   1: protected override void Draw(GameTime gameTime)
   2: {
   3:     graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
   4:
   5:     Rectangle rect;
   6:     rect.X = 0;
   7:     rect.Y = 0;
   8:     rect.Width = graphics.GraphicsDevice.Viewport.Width;
   9:     rect.Height = graphics.GraphicsDevice.Viewport.Height;
  10:
  11:     spriteBatch.Begin();
  12:     spriteBatch.Draw(background, rect, Color.White);
  13:     spriteBatch.Draw(ball, Vector2.Zero, Color.White);
  14:     spriteBatch.End();
  15:
  16:     base.Draw(gameTime);
  17: }

Line 13 is responsible for rendering the ball. Hit F5 and you should see something like this:image

Attention: Notice how the order of call between the Begin and End of SpriteBatch matters? It will draw the textures on top of each other based on that order. If you reverse the order of drawing of the backdrop and the ball, you won’t see the ball anymore.

So let’s say that this is a game that I am making, and after a while, the ball gets some damage or something and we want to change its color to indicate that something happened to it. How do we do that? We can use another texture that is of that color I guess, but there is an easier way:

 

   1: spriteBatch.Draw(ball, Vector2.Zero, Color.Red);

This is how I am rendering the ball now. Instead of using Color.White which means “draw as is”, I am using Color.Red which means mix the colors of the texture with the color red. In this case, adding Red to White will give you Red:

image

There you go! We changed the color of the ball with a simple change in how we draw it. You can imagine making the Color argument of the Draw method a variable in your code. You can then change its value in the Update method of your game based on whatever criteria you come up with and the Draw call will always pick up that new value. In a simple fighting game I prototyped, I would add a red tint to my fighter’s colors for 1 second or so to indicate that he was hit by the other player.

Ok! That’s it for today! Next time I’ll talk some more about textures and get into how you can animate them! Getting closer to making games!

Moving Stuff Around in XNA!

December 5th, 2007

In my last post, we created a very simple “Hello World” game in XNA. It wasn’t anything fancy, but it served the purpose of introducing XNA project template and getting us familiar with what’s in the code. But let’s face it, it wasn’t a game… not even close to being one. Putting text on the screen that doesn’t move is quite boring. Time to spice things up a bit and get to learn about user input while we’re at it.

You can reuse the project we created from last post if you want, or create a new one. Whichever is fine by me! Instead of boring text, we’ll use some “graphics” this time. I use the term “graphics” very loosely since the best I could come up with was this little image:

ball

Yes, not very exciting eh? It’s just a ball. You can use any image you want, you can even right click on this one and save it to your PC and use it. It’s all good. Just get an image, one that is not too big though, this one is 200×200 pixels. I saved this one as ball.png.

Tip: The reason why I saved this as a .png file is to preserve transparency. The image is actually square in shape. But the area around the circle is transparent, hence why you can’t see it. I used Paint.Net to create the image and save it as a png. We’ll learn more about images and transparency later. So don’t worry too much about it now. Make a quick stop at my “Preparing your toolbox!” post to get a list of the tools I use, including Paint.Net.

Ok, so now you should have your image file ready to use. As I said, mine is called ball.png. Once I have the project created, I went ahead and added the image to my Content folder:

image

This time, we’re adding an Existing Item vs a New Item. You’ll get a regular “Add Existing Item” dialog, find your image file and click on the Add button to add it to your Content project.

Tip: If you take a closer look at the Add button, you’ll notice a little arrow on it. Clicking that arrow will expand the button to show a menu:

image

Picking “Add” will add a COPY of the file to your project. Picking “Add As Link” will add a LINK to the file in your project. Why do you care? well, if you use Add as Link option, you can still make changes to the image and not have to worry about either recopying it to your Content folder or modifying the now newly copied version instead. The bad thing though is that if you forget and then send the source code to someone else, they won’t have the linked image and will fail building the game.

I use Add most of the time to avoid that, just need to remember to re-open the new copy in my editing program if I need to modify it.

Ok, so now you should have the new file in your Content folder. Mine looks like this:

image

Now let’s add the required code to load it up. All code is in Game1.cs.

First thing you want to do is add a Texture2D that we will use to load the image into. While you’re at it, add a Vector2 variable that we can use to track where to place the ball on the screen. My code looks like this: (see lines 3 & 4)

 

   1: GraphicsDeviceManager graphics;
   2: SpriteBatch spriteBatch;
   3: Texture2D ball;
   4: Vector2 ballPosition;

In the Initialize method, I will instantiate ballPosition and give it an initial value: (line 3)

 

   1: protected override void Initialize()
   2: {
   3:    ballPosition = new Vector2(20, 20);
   4:    base.Initialize();
   5: }

Nice! Now let’s load the image in the Texture2D we created: (line 7)

 

   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 image            
   7:     ball = Content.Load<Texture2D>("ball");
   8: }

And finally, let’s render it just like we did for the “Hello World” example:

 

   1: protected override void Draw(GameTime gameTime)
   2: {
   3:     graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
   4:
   5:     spriteBatch.Begin();
   6:     spriteBatch.Draw(ball, ballPosition, Color.White);
   7:     spriteBatch.End();
   8:
   9:     base.Draw(gameTime);
  10: }

Few things to note here: (line 6)

  1. See how we’re using spriteBatch.Draw this time vs DrawString? That’s because we’re Drawing an image.
  2. We are using ballPosition as the position on the screen to draw the ball at. We are not creating a new Vector2 everytime. Much cleaner and will be useful in the coming part.
  3. We use Color.White as the Color to use to draw the image with. That means “Draw the image as is, don’t mess with the colors at all!”. If you specify something like Color.Yellow, the image will have a Yellow-ish tint to it. Using Color.White is what you want unless you want to mess with the colors.

Alright! There you go! Hit F5 and you will see your image rendered as expected! Neat eh?

Moving the Image Around

While rendering an image is cool and all, let’s take it a step further and let the game allow the user to move that ball around! Time to add some user input!

So how do we do that? I would like to use the keyboard arrow keys to move the ball up, down, left and right. So we will need to somehow read what keys the user is pressing now and then change the position of the ball to match the direction they are pressing. This turns out to be super easy to do!

First though, we need to figure out where we’ll put this code in our project. This is something we want to do on a regular basis. Something that will update the position of the ball on the screen. So we’ll put the code in the Update method of course!

 

   1: protected override void Update(GameTime gameTime)
   2: {
   3:     // Allows the game to exit
   4:     if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
   5:         this.Exit();
   6:
   7:     KeyboardState keyboardState = Keyboard.GetState();
   8:
   9:     if (keyboardState.IsKeyDown(Keys.Up))
  10:     {
  11:         ballPosition.Y -= 5;
  12:     }
  13:
  14:     if (keyboardState.IsKeyDown(Keys.Down))
  15:     {
  16:         ballPosition.Y += 5;
  17:     }
  18:
  19:     if (keyboardState.IsKeyDown(Keys.Left))
  20:     {
  21:         ballPosition.X -= 5;
  22:     }
  23:
  24:     if (keyboardState.IsKeyDown(Keys.Right))
  25:     {
  26:         ballPosition.X += 5;
  27:     }
  28:
  29:
  30:     // TODO: Add your update logic here
  31:
  32:     base.Update(gameTime);
  33: }

This is it! Let’s have a closer look, shall we?

  • For now, ignore lines 4 & 5 which are the default code in that method. They just let you press the Back button on a Xbox 360 gamepad that is connected to your PC to exit the game.
  • Line 7: To get information on what keys are pressed, you want to talk to the Keyboard. To do that you use the Keyboard class from the framework. You ask it to return to you a snapshot of the state of the keyboard at the time you made the call. So you use Keyboard.GetState() which returns a KeyboardState object. This object has all the information about which keys are currently pressed, released, etc at the time of the call. Hence the “snapshot”.
  • I assigned keyboardState to hold the return value from Keyboard.GetState()
  • Lines 9 – 27: Now we start to see what keys are pressed. The basic idea is to see which key is pressed and update the X or Y of ballPosition to match that direction.
  • Remember, incrementing the Y value means move position downward and incrementing the X means go right.
  • Should be clear now what we’re doing. We are checking which key is pressed and moving the ball in the corresponding direction (for instance, left arrow means move to the left which means decrement the X) and we change the value by adding or subtracting 5 pixels.

That’s it! You’re done! Hit F5 and when the game comes up, move your image around using the up/down/left/right arrow keys on your keyboard! See? things are starting to look like a game…kinda. We’ll get there!

"Hello World!" in XNA

December 4th, 2007

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:

Solution Explorer View

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”:

image

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:

image

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:

image

This will add a new file to your Content project called “SpriteFont1.spritefont”:

image

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:

image

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!

Your First Game!

November 23rd, 2007

Alright, I’ll be honest from the get go… this won’t really be a “game”. It won’t be interactive, and it most certainly won’t be fun. What it will be though is a game based on the XNA Game Framework and will use the graphics card and all that good stuff. Consider it the “Hello World” of gaming if you will. Let’s see how this will work!

First thing is to make sure you installed XNA Game Studio by following this post. Once you got that up and running, let’s create our “Hello World!” game.

Fire up your Visual Studio (Pro or C# Express) and click on File menu, New and then Project. You should see something like this:

image

Notice how we expanded the Visual C# node to reveal the XNA Game Studio node? Make sure you do that. This way you will be able to pick from the Game Studio project templates. Pick Windows Game (2.0) and hit Ok.

When the project is done creating itself, you are ready to test it out! Hit F5 and the project will build and run. If all goes well, you should see the default CornFlowerBlue window:

There you go! That’s your very first game! It’s running on the XNA Game Framework which in turn uses Microsoft DirectX.

In the next post, we’ll break down the source code to see what is going on and understand how this works. It’s pretty simple actually. To make this a true “Hello World”, we’ll even add a “Hello World” text in this game next time ;)

Preparing your toolbox!

November 13th, 2007

Now that we’ve been through the basics of how a game works (Anatomy of a game series starts here), it’s time we start to actually create our own games. Before we do that though, we’ll need to put together a collection of tools that will help us along the way.

The Framework!

The primary software development kit we will be using to develop games is the XNA Game Community Platform. It’s the obvious choice for me since I work on that team ;) But really, it’s a very good and easy to use framework. With XNA Framework, you will be able to develop games that run both on Windows and your Xbox 360. How cool is that?

So how do you get started with XNA Game Studio Express (XNA GSE)? Simple, follow the Getting Started instructions prepared by the XNA Community Game Platform team. Once you install XNA GSE, do yourself a favor and create a new project and use the Spacewars starter kit. It’s a ready to run game that is quite entertaining and should wet your appetite for what you can do with the framework.

Update: XNA Game Studio 2.0 Beta has just been released. You probably want to pick this one up since that’s the version I will use for my blog. You can get it from here.

Graphics Creation Tools

Now that you have XNA GSE set up and running, you will want to fetch some basic content editing tools. By content, I mean graphical content like images, 3D models and so forth. We’ll start simple at first, so in reality, something like Microsoft Paint will do fine at first, but it won’t harm us to get a good set of tools off the bat.

Image Creation/Editing tools:

For starters, let’s get us a couple of programs that we can use to create and manipulate images:

Paint.Net

Paint.Net is a very cool image manipulation program that is written in C# and .NET. It does what we need very well and comes at a very good price: Free. You can pick up a copy from Paint.Net website. You will quickly learn to love this little program!

Gnu Image Manipulation Program (GIMP)

This is one of my favorite tools to use. If you’re familiar with Adobe Photoshop, then Gimp will make a lot of sense to you. Gimp is basically an open source alternative to Photoshop. You can do a whole lot of really cool stuff using Gimp. So when the job is bigger than Paint.Net can handle, I jump over to Gimp to get it done! Gimp is open source and runs on a lot of different Operating Systems including Linux, Windows, Mac OS X, etc. The official Gimp site is here. But you’ll probably want to download the Windows version which is provided as an installer from here.

3D Modeling

When we get to 3D graphics, we’ll want to start messing around with creating and editing 3D models. There are a lot of tools out there that we can use. The ones I am somewhat familiar with are:

SoftImage XSI Mod Tool

SoftImage XSI Mod tool is a free lite version of XSI’s bigger and professional 3D modeling package. The cool thing about this version is that it is XNA aware. SoftImage have done a lot of work to make this version work very well with XNA. Go pick up a copy from their official website.

Blender

Open source strikes again! Blender is the Gimp of 3D modeling tools pretty much. Blender is a pretty powerful, yet somewhat difficult to use, 3D modeling package that is totally free. There is a lot of documentation provided by Blender and the community to teach you how to use it. Just like Gimp, Blender runs on a variety of operating system including Windows. Blender can be downloaded from their official website.

Wings 3D

This one is a pretty cool quick and dirty modeling tool. If you want to throw together a decently looking model pretty quick (read: Programmer’s Art), then you will want to use Wings 3D. Grab a copy from their official website.

Misc Tools

Last but not least is a collection of useful to have tools.

Notepad++

Every one should have some sort of text editor that they are comfortable with. The one I am using now is Notepad++. Simple to use, has syntax highlighting, etc. There are a lot of other good editors out there, you probably already have a favorite one.

Powershell

Your toolbox is not complete without a good and solid command shell. You can always use the Windows cmd.exe shell. It works fine and will take care for *most* of your needs. But when you start looking for real power and flexibility, you want Powershell. Powershell is Microsoft’s new command shell that is based on the .Net framework. It is simply amazing and fun to use. You have full access to all the .Net framework directly from the shell or in your scripts. Scripts use a C# like syntax which is easy to pick up. There is a lot to know about powershell, you can always start with my Powershell section of my blog.

Final Thoughts

Everyone’s toolbox is very custom to their needs, you will end up with a set of tools that is much larger than the ones I listed here. Eventually, you may end up replacing all the ones I mentioned with other more powerful ones. This list is a beginning of sorts, learn to use these tools and you’re journey in game development will be that much easier. As I start talking about more topics, I will always point out some cool tools that make life easier for that specific topic.

Anatomy of a Game – Part 5

November 7th, 2007

This post will talk about Effects. Effects are probably one of the coolest aspects of graphics programming. To understand them, you first need to have some background history.

Graphics initially were entirely rendered by the CPU. This meant that all the calculations that were involved in transforming a 3D world to a 2D image were done by the CPU. It gave decent results, but performance was not very good. That’s when the first 3D accelerator cards started to show up on the market. These cards could do a lot of those calculations on a dedicated CPU that lived on the graphics card. So instead of doing all the calculations, the CPU would send the vertices to the card along with where the camera was in the world, and the graphics card would figure out what image to draw on the screen.

The problem with these cards, though, was that they had what is called a fixed-function pipeline. That means that the algorithms that were used to calculate how to render the world were fixed on the card. They did the job pretty well, and even included lighting, but they did it in a limited way. So if you wanted to have any kind of cool effect on your world, you couldn’t do that on the card.

Programmable cards came to the rescue! These cards, which are the majority now, let you tell them exactly how to perform the calculations needed to render the final image. You write small programs called shaders that run on the card and that perform the work needed to generate the final image you see on the screen. This advance has allowed game developers to come up with all kinds of awesome effects that make their games look really cool, and since they run on the fast graphics processor, they don’t drag down performance. This shader code is referred to as effects.

So what can you do with effects? At the simplest level, you need to write them to tell the graphics card how to render the final image to the screen. That involves doing some simple math (that is very well documented and known) to tell the graphics card how to render the scene to the screen. You can also include more calculations to apply lighting to the scene. When you’re done rendering the image, you can have the graphics card run yet another piece of code on the final image to give it a blur effect, for example. If you’ve ever used a package like Photoshop and played around with the filters it has, then you can get a feeling as to what you can do with shaders. You can do all kinds of cool effects on the final rendered image that happen at real time. Things such as water, reflections, blur, bloom, and so on are possible thanks to effects.

Anatomy of a Game – Part 4

November 7th, 2007

Another part of the grand illusion that game developers are creating is lighting. You can use the concept of lighting to illuminate certain parts of the world in a realistic way. Of course, there is no real light shining on anything; it’s all a simulation of how the objects will look when light is bouncing off of them.

Light in games is usually specified by a color and a direction vector. This information is used to mathematically derive the exact look of every pixel in the screen based on how the light bounces off of it, the color of the light when combined with the color of the pixel, as well as any properties of the material that this pixel is part of. In order for lighting to work, every vertex in your world needs to define what is called a normal vector. A normal vector is a vector that points in the direction that is perpendicular to the surface that the vertex is part of.

clip_image002

The reason you need that normal is that light calculations use it to know how much of the light bounces off a surface. By calculating the angle where the light hits the vertex normal, you can tell if that light is going to reflect or not and by how much. By calculating this information for all the vertices and using it to darken and lighten each pixel, you get the illusion of a well lit object.

clip_image004

In this example, the light is hitting the sphere model from the top left corner. As you can see, the light reflected relatively accurately by making the parts of the sphere that are facing towards the light brighter and the other areas darker. That’s because the normals on every vertex close to the light calculated a strong reflection angle for the light, while the other normals that are facing away from the light did not reflect much of it. It will make more sense when you actually try it.

Move on to part 5

Anatomy of a Game – Part 3

November 7th, 2007

So what are the different elements that go into making a 3D game? Let’s start by familiarizing you some terms used in 3D programming, so that when you’re working on your game, you’ll have an idea of what’s going on.

Game Camera

One of the first concepts you’ll see when working with 3D graphics is the game. Camera, you say? What is a camera doing in a game? The principle is quite simple, and is not required for 2D games. In 2D games, your “world” is bound by the X and Y axes only. So your view of the game is a top-down view of the game grid. In 3D, however, you have another axis, the Z axis. So how do you position your view of the game world? That’s what the game camera does for you.

In simplest terms, the game camera is the hypothetical camera that someone is holding and through which they are filming the action in your game. What you see on your screen is what the camera sees. So imagine you have a ball sitting on a table and someone is holding a camera and is filming that ball while moving around it. What you end up seeing on the TV later is the ball from every direction as the camera is rotating around it.

It’s the same thing in 3D graphics. A game camera has a position in the world just as anything else has a position. So in 3D graphics, the camera position is a value of x, y, and z that tells the game where your camera is positioned in the world. That means the camera can have objects behind it and you are not going to see them. The other important value that you need to specify is a position in the world for the camera to look at. If you don’t specify that value, then how is the camera going to know where to point once it’s placed in the world? So a camera can be positioned at, say, 0,0,100 and be looking at 0,0,0. This means it is positioned 100 units away from the origin of the world and is pointing toward the origin. So if you have an object that is at 0,0,50, you will see it. If there is an object at 0,0,200, you won’t see it because it’s behind the camera. You can do all kinds of cool zooming and rotation effects by moving the camera position in the world every frame! Turn your code into a director and a camera man and go wild!

The camera has other settings, such as the Up direction, the field of view, near and far planes, and so on. Once you start working with 3D graphics, all those things will be very clear and easy to understand. I just wanted to explain the purpose and need for having a camera in a 3D game.

Vertex

Since we started talking about 3D graphics, I’ve been mentioning that everything in the world has a position x,y,z. In its simplest form, a vertex is a position in the world. More specifically, a vertex is a data structure that you declare and use as the building block of your entire world. So to draw a square on the screen, for example, you would specify four vertices that define the four coordinates of that square. A vertex has a position element in it that is of type Vector3. That position element is where you store the values for the x,y, and z for a particular point in space.

A vertex can also have other information in it. In fact, you can define your own vertex structure and include as much data in it as you need. A typical simple vertex structure, though, would contain a Vector3 position (x,y,z) and a Color element. This means for every point in the world, you can specify its position and color. What does that color do exactly? Well, if you specify a different color for each of the four vertices you used to create a square, you can get an image that looks like this:

clip_image002

In this image, the vertices have the colors blue, green, red, and yellow. What the graphics card did for you was fade one color to the other in the way you see in the illustration. Had all vertices had the color black, the square would just be, well, all black. Pretty neat, eh? Ok…not too useful, but still neat!

DirectX and thus XNA Framework define a few popular vertex structures that have different elements besides position in them. VertexPositionColor is one that you can use to create something like the square above. The cool thing is that you can create your own if you find yourself needing something more custom. It’s pretty easy to do.

Mesh

Ok… so now that we learned what a vertex is and how it is the building block of anything in the world, it’s time we learned how we can build shapes using them. The square we talked about creating in the previous section is just a collection of four vertices that got together to create that square. If you’ve ever played “connect the dots” on paper before, you are already familiar with the idea of meshes.

A mesh is a collection of positions in the world that, when connected together, form a shape. The following diagram shows a simple cube mesh that is made up of eight distinct vertices in the 3D world:

clip_image004

This is a simple mesh, of course, and has only eight vertices. The more vertices you have, the more detailed and complex your mesh can be:

clip_image006 image

So as you can imagine, everything you see today in a game like Halo or Gears of War is composed of such meshes—all the characters, guns, vehicles, banners, terrain, buildings, and so on. To create such meshes—or models, as they are called —you use some drawing package such as 3D Studio Max, Maya, Softimage, and so on. These packages make it easy to draw such intricate models and export them in a format your game can load and transfer to a collection of vertices that your graphics card can render. The XNA Framework can draw meshes with the Model class, which is a group of several meshes.

Materials

So now that you have a cool model of a car or spaceship, how do you actually make it look all cool and colored? You see how uninteresting the model looks when it’s “naked” and not colored and polished. That’s where materials come into play.

Just as you might create a model out of clay and then paint it to give it color and detail, you do the same in 3D graphics. You apply a material to a model that specifies the color of that model or part of the model. Materials also include information such as how much light they reflect, whether they are plastic or wood-like in appearance, and so on—just as there are different materials in the real world that have specific properties. Plastic tends to be very shiny and reflects a lot of light; wood is not generally shiny and doesn’t reflect light as much. Leather has a very distinct look to it, and so does metal. You get the idea.

You can define a material for your model that gives it a unique look in the world. Armor on a futuristic soldier, for example, could have a material that is very reflective. To add more detail, a material can have a texture. A texture is an image that is overlaid on a model to give it more detail. Think of it like a decal that you put on a toy airplane model to give it a more realistic look. A texture can be an image of grass that you apply to your terrain to make it look more real, or an image of a suit that you put on a model of a person to give them clothes. The texture will be affected by the other properties you have on your material that affect how much light it reflects, and so on.

Materials are usually created by your graphics package along with something like Photoshop to create the textures. You map that material on your model and then export the entire model and load it in your game. The end result will be a mesh object along with its related set of materials that may or may not include textures. The Gears of War model above will look quite different when you apply materials to it:

Big difference eh? When you start messing with this aspect of game development, you really start to develop a huge appreciation for artists.

Move on to part 4

Anatomy of a Game – Part 2

November 7th, 2007

In this post, let’s talk about the difference between 2D and 3D games!

Games can be either two dimensional (2D) or three dimensional (3D). Before we continue talking about the two types and how they differ, let’s talk about how they are similar.

Remember, games are nothing but elaborate illusions. Your monitor is capable of displaying only 2D images. That’s why your resolution is something in the form of width x height (1600×1200, for example). You don’t see a monitor that is advertised as 1600×1200×800! So how does it make sense that we can have 3D games on a 2D display surface? It’s really nothing but an optical trick that artists have been using for ages. You can draw a 2D image and put depth in it by how you size things relative to each other as well as how you draw the lighting and shadows in it. It’s just an illusion. Here’s a perfect example of such an illusion:

The image looks like it’s 3D when it’s 2D but with amazing usage of lighting, perspective, shadows, etc. This is really what 3D gaming is about, how to draw such 2D images in realtime in an easy way. Lots of math!

We’ll discuss 2D games first since they are easier to understand than 3D ones. In a 2D game, you have a canvas (your screen or game window) that has a height and a width. We are going to assume that your game is running full screen at a resolution of 1600×1200. That would mean that the coordinates of the upper left corner of the screen are 0,0, and those of the lower right corner are 1600,1200. You can express any point on the screen as an x,y pair of positive values.

Programming for 2D is really pretty easy. You start by positioning your objects on the X,Y grid, and then you move them around. So you can start by putting a paddle for the game Pong at the coordinates 20,20 and then moving it around the screen by increasing and decreasing the Y value to make it go up and down. So for the first frame, you put it at 20,20, and then in the next frame, you position it at 20,21, and so on. As the game draws itself frame by frame, your paddle will appear to move down when actually it’s you who are positioning it at a slightly lower point every frame. You can do the same thing with the X value to make it move sideways.

So what do you do for 3D then? Well, in principle, it’s kind of the same at the core, but needs different considerations than 2D. The first thing is that you specify a location on the screen by three values, the 2D X and Y values and a new value called Z that we’ll use for depth.

clip_image002

The Z axis goes through the screen. This means that you can specify points in this 3D space that are at different depths from each other. So in essence, an object can be placed way behind another one and appear to be smaller in size because it’s further away. What happens is that you specify objects in this 3D space with different depths. Then when the graphics card draws the final image that appears on your screen, it will apply all kinds of mathematical operations to produce a 3D looking image that is really 2D. But for all intents and purposes, you are working in a 3D space and have to account for that in everything you do. That means when you want to know whether one object hits another, you have to consider that they may be at different depths (that is, one is behind the other).

Whether your space is 2D or 3D, you’ll find that a lot of the principles remain the same. You still have to specify positions of objects on the screen by giving them coordinates. Moving objects around is an act in manipulating these coordinates to position them in another place. 2D is simpler because you don’t have to worry about a whole other axis, but moving to 3D doesn’t complicate life that much once you get it.

Move on to part 3