Archive for December, 2007

Happy Holidays Everyone!

December 24th, 2007

Just wanted to make a quick post wishing everyone Happy Holidays and Happy New Year! I hope everyone is having a great time celeberating! More tutorials coming your way soon :) In the meantime, enjoy the holidays!

Time for Input!

December 19th, 2007

Now that we have learned how to render basic 2D textures and can actually start making a game, we probably should talk about how Input works in a game. Unless your game is one where the player has to sit there and just stare at it (at which point you’re probably attempting a hypnosis game for some disturbing reason… do let me know if you got a working version though), you want to have them actually control something in it. So how does Input work in XNA Game Framework? Turns out that it’s pretty simple actually. Let’s talk Input!

Overview of how Input works

Input in XNA Framework is quite simple to use you’ll be pleasantly surprised. You can read input data from a keyboard, mouse and variety of supported game pads (Xbox 360 controllers, Guitar Hero controller, Rock Band drums, etc).

Where in my code do I read and process input? Simple: In the Update method of your Game class! To read input, you will be using one of the following 3 classes based on the device you want to read from:

  1. Keyboard Class: For keyboard input
  2. Mouse Class: For reading the Mouse input
  3. GamePad Class: For reading from a varitey of supported gamepads and controllers.

The way it works is that every one of these classes has a GetState() static method that you call. This method returns either a KeyboardState, MouseState or GamePadState object back to you. This object has data for the state of the input device when the GetState() method was called. So for instance, the MouseState object will have information such as mouse cursor location, the state of all the buttons on the mouse (pressed or released) and the scroll wheel value. You simply read the values and act on them.

Here’s a thought for you though. The call to the GetState() method returns a snapshot of the state of the device at the time you made the call. Since you call this in the Update() method of the game class, it gets called 60 times a second. So if for instance you are writing a shooting game and will have the player use the mouse button to shoot, you might check the MouseState.LeftButton property to see if the button is pressed or released. If it’s pressed, you will have the game shoot. The nasty surprise you’ll quickly run into though is that the game will fire at an alarming rate vs just one shot per mouse click! Why? Because you are checking on the Pressed button state in the Update loop that gets called 60 times per second. Since most players can’t click and release the button in 1/60th of a second, they probably will have it held done for longer and all those will come through as Pressed giving the wrong result of multiple shots until the button is released.

So how do you deal with that? The answer is quite simple. Let me show you via some code. Let’s say we want to check if the left mouse button was pressed or not. The code would be as follows:

First we declare a member variable in our class of type MouseState (line 5):

   1: public class Game1 : Microsoft.Xna.Framework.Game
   2: {
   3:     GraphicsDeviceManager graphics;
   4:     SpriteBatch spriteBatch;
   5:     MouseState previousMouseState = Mouse.GetState();

We initialize the variable by calling Mouse.GetState() like in the code. This grabs the state of the mouse when the game is about to start.

When we read the state of the mouse in the Update code, we want to register a mouse click when the CURRENT state of the left mouse button is Released and PREVIOUS state for it was Pressed. This way we will know that the button was pressed and just got released at the time we called GetState(). Then at the end of the Update method, we save the Current MouseState we just read as the PreviousMouseState so that we can use it next time Update is called. Here, check out the code, it will become very clear:

   1: protected override void Update(GameTime gameTime)
   2: {
   3:     // Grab the current state of the mouse
   4:     MouseState CurrentMouseState = Mouse.GetState();
   5:
   6:     // Now we see if the left mouse button was clicked or not
   7:     if (PreviousMouseState.LeftButton == ButtonState.Pressed
   8:         &&
   9:         CurrentMouseState.LeftButton == ButtonState.Released)
  10:     {
  11:         // Left mouse button was clicked! 
  12:         // Do something with it!
  13:     }
  14:
  15:     // Record the CurrentMouseState
  16:     // as PreviousMouseState
  17:     PreviousMouseState = CurrentMouseState;
  18:
  19:     base.Update(gameTime);
  20: }

Let’s dissect the code:

  • Line 4: We get the current state of the mouse and save it.
  • Lines 7-9: We check to see if last time we called update the button was pressed and now it is released. This means we got a mouse button click!
  • Lines 11,12: Do whatever the game is supposed to do in response to a button press (shoot something)
  • Line 17: Save the CurrentMouseState in PreviousMouseState so that you can use it next time Update is called.

Simple eh? The same method applies to Keyboard and GamePad classes as well. Just save the previous state and compare it with the current state. This way you can get a clear reading of when a player has pressed a button or not. Some game play actions of course require the player to keep a button pressed for instance, these don’t need such a method, you just check if the button is pressed or not and do whatever action in response as long as the button remains pressed.

Just for completness sake (and to make this post look bigger and more important that it really is), here’s some code for how this works for both a Keyboard and a GamePad.

Keyboard

Here’s the code to check for the Left arrow key on the keyboard, I removed all non-essential parts:

   1: public class Game1 : Microsoft.Xna.Framework.Game
   2: {
   3:     GraphicsDeviceManager graphics;
   4:     SpriteBatch spriteBatch;
   5:     KeyboardState previousKS = Keyboard.GetState();
   6:
   7:     protected override void Update(GameTime gameTime)
   8:     {
   9:         // Grab the current state of the mouse
  10:         KeyboardState CurrentKS = Keyboard.GetState();
  11:
  12:         // Now we see if the left mouse button was clicked or not
  13:         if (previousKS.IsKeyDown(Keys.Left)
  14:             &&
  15:             CurrentKS.IsKeyUp(Keys.Left))
  16:         {
  17:             // Left arrow was pressed! 
  18:             // Do something with it!
  19:         }
  20:
  21:         // Record the CurrentMouseState
  22:         // as PreviousMouseState
  23:         previousKS = CurrentKS;
  24:
  25:         base.Update(gameTime);
  26:     }
  27: }

GamePad

Now let’s see how this works for a GamePad like the Xbox 360 controller:

   1: public class Game1 : Microsoft.Xna.Framework.Game
   2: {
   3:     GraphicsDeviceManager graphics;
   4:     SpriteBatch spriteBatch;
   5:     GamePadState previousGS = GamePad.GetState(PlayerIndex.One);
   6:
   7:     protected override void Update(GameTime gameTime)
   8:     {
   9:         // Grab the current state of the mouse
  10:         GamePadState CurrentGS = GamePad.GetState(PlayerIndex.One);
  11:
  12:         // Now we see if the left mouse button was clicked or not
  13:         if (previousGS.Buttons.A == ButtonState.Pressed
  14:             &&
  15:             CurrentGS.Buttons.A == ButtonState.Released)
  16:         {
  17:             // A button was pressed! 
  18:             // Do something with it!
  19:         }
  20:
  21:         // Record the CurrentMouseState
  22:         // as PreviousMouseState
  23:         previousGS = CurrentGS;
  24:
  25:         base.Update(gameTime);
  26:     }
  27: }

Check out Line 5, do you notice the argument to GamePad.GetState? That’s the PlayerIndex enumeration value you need to specify. Since an Xbox can have up to 4 controllers plugged in, you need to specify which one you want to read from. In this case, we specified PlayerIndex.One meaning controller #1. To read input from multiple controllers, you need to declare PreviousGameState variables for each PlayerIndex you want. Just do the same thing for more than one controller like you would for one.

Final thoughts

One of the things you might want to do is write an input handling class for your game. Something to encapsulate all the input handling code for your game. You can go totally wild with how you implement it. You can make it event driven so code can subscribe to certain events such as “AButtonPressed”, etc. Be creative! These classes will live with you for a long time ;)

Quick Questions, Quick Answers!

December 18th, 2007

For this post, I decided to spend some time answering some frequently asked questions that some of you may or may not be thinking of right now. I remember at this stage of my learning, I started to wonder about how to do certain things. So let’s dive right in!

Eh…where’s my mouse pointer?!

Yeah…this is one I had pretty quick after using XNA Game Studio. I noticed that whenever I ran my game and moved the mouse over it, POOF!, the mouse pointer is gone. Working on the team that develops XNA has the awesome benefit of me being able to walk up to one of the developers and be like “yeah…dude…wtf?”. The answer is pretty simple, putting the following code in your Initialize method will make the mouse pointer visible:

this.IsMouseVisible = true;

The default value is “false”, hence why we don’t see it by default.

I want to run my game at a different resolution, how?

Pretty soon after you start playing around with XNAGS, you will want to run your game at a different resolution than the default one. How do you change it? Here’s the code:

   1: public Game1()
   2: {
   3:     graphics = new GraphicsDeviceManager(this);
   4:     Content.RootDirectory = "Content";
   5:
   6:     // Set the game's resolution to 1680x1050
   7:     this.graphics.PreferredBackBufferWidth = 1680;
   8:     this.graphics.PreferredBackBufferHeight = 1050;
   9: }

Simple :) Just make sure it’s in the Constructor vs the Initialize method.

Give me fullscreen!

Alright, a follow up question is: How do I make my game run in Fullscreen mode?

   1: protected override void Initialize()
   2: {
   3:     // If we are not Fulscreen, let's be fullscreen!
   4:     if (!graphics.IsFullScreen)
   5:         graphics.ToggleFullScreen();
   6:
   7:     base.Initialize();
   8: }

You can do it by either calling the ToggleFullScreen() or directly setting the value of IsFullScreen to true for fullscreen or false. Both work just fine. See? We want you to have options!

How do I tell if my game is “Active” or in focus?

This is one that I ran into when I was working on a simple sample. I used the mouse to control the sample (was rotating a cube or something amazing like that) and I noticed that when I moved the mouse when the game wasn’t active and the cube still rotated. Hmm..that’s odd. Why is my game handling mouse movements even when it’s not the actively focused application? My first thought was “Aha! BUG! The devs screwed up! Time to go rub it in!”. Five mins later, I come back after talking to one of the devs and it’s not a bug (sigh…fine..almost had him). This is what you want to do:

   1: protected override void Update(GameTime gameTime)
   2: {
   3:     if (this.IsActive)
   4:     {
   5:         // Add code that you only want to run when 
   6:         // the game is the active and in focus
   7:         // application. 
   8:         //
   9:         // Stuff like input handling for instance is good 
  10:         // here.
  11:     }
  12:
  13:     base.Update(gameTime);
  14: }

All you need to do is check the IsActive flag. If it’s true, your game is in focus.

My Update method is called 60 times per second, I want faster!

The Update method gets called by default 60 times a second. This makes sure that your game runs at the same pace on any device it runs on. But sometimes you may want to change that to make it run as fast as possible. This means you want it to be called as often as possible by the XNA Framework. To do that, here’s the code:

   1: protected override void Initialize()
   2: {
   3:     this.IsFixedTimeStep = false;
   4:
   5:     base.Initialize();
   6: }

and in the Update method, you can find out how long it has been since the last Update call like this:

double elapsedTime = gameTime.ElapsedGameTime.TotalMilliseconds;

That’ll do it.

How to I set the title of the game window?

Alright, this one you probably would have spent like 20 seconds to find out how to do. But hey, I just saved you 20 seconds eh? Yeah…that’s how I roll.

Setting the title of the Window in non-Fullscreen mode is useful since it’s an easy and fast way to display some short debugging info for example. Something like Frames Per Second can be displayed here pretty quickly. This is how to do it:

   1: protected override void Initialize()
   2: {
   3:     this.Window.Title = "I am an awesome game! No really!";
   4:
   5:     base.Initialize();
   6: }

See? now you have 20 seconds extra to do whatever with.

That’s it for now! If you have any other questions, post them as comments and I’ll see that they get some sort of an answer. Have fun!

XNA Game Studio 2.0 RELEASED!

December 15th, 2007

I am very excited to share the news about XNA Game Studio 2.0 having been released! You can grab your copy from here. Ok, fine, my post is a few days late (XNA Game Studio 2.0 was released last Thursday 13th Dec), but I have an excuse! I got on an airplane heading back home to Egypt to visit my family. I am in Egypt now and just barely got over the jet lag and the inital storm of “hey! nice to see you!!”. So what’s new??

Here’s a quick list of what’s new in this awesome version:

  • Networking Support
  • Expanded Support for Visual Studio 2005 Products (that means Visual Studio 2005 Pro and up, an no, no support for Visual Studio 2008)
  • XNA Game Studio Device Center and Easier Xbox 360 Connectivity
  • Cross-Platform Game Project Converter
  • Updated Game Project Format
  • Integrated Game Content Projects
  • XNA Game Studio Package Utility
  • Updated Microsoft Cross-Platform Audio Creation Tool (XACT)
  • Parameterized Processors
  • …and more! Have a look at the “What’s new” page in the docs for the full list of changes.

All my tutorials have been done using XNA Game Studio 2.0. So it’s a good idea to upgrade to that version if you haven’t by now.

Have fun! I will get to writing my next tutorial very soon. Just gotta get to feeding my camel first.

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!