Archive for the ‘Beginner Game Tutorials’ category

Back from the dead! With a link :)

September 3rd, 2009

Yes..yes…I am still alive. Just that I have been a bit busy with a little project called Natal. But I just ran into this really cool link and I just had to share it:

http://www.gamedev.net/reference/art/features/blender1/

Learn how to make game models with the free 3D modeling package Blender.

Enjoy!

Creating your World

September 23rd, 2008

Today I want to talk to you about one of the important subjects of game development. Creating your world. Your game lives in some world (usually), how you design and build that world is something you want to think about early on regardless if it’s a 2D or 3D game. Since we’re still learning, let’s focus on 2D first. This will be a mini series of posts that will walk you through creating a 2D world, the tools you can use and how we can code it up in our game. We’ll even touch on some semi-advanced features of XNA Game Studio such as custom content pipeline extensions. Don’t be scared now! It really sounds way scarier than it actually is. So let’s get started!

So what is a 2D world?

In a 2D game, a world is really the map you’re playing on. Let’s have a look at some examples:

super-mario-bros.jpg

Here’s a classical screenshot of Super Mario Bros. You can see that the world is the sky, pipes, clouds, bricks, etc that Mario is running around in.

Here’s another one. This is from Zelda, a game that is so popular that people think I am wasting their oxygen because I never played it or got into it :/

How are such worlds created? Well… that’s the easy part :)

Creating a 2D world

These worlds are created using a technique a lot of us learned at childhood: Tiles! Yep… that’s all they are. The world is composed of a set of tiles that are arranged on a grid to give the final look. So to create a world like the one in the Mario screenshot above, you need a tile that is totally blue in color for the sky, one that looks like bricks for the ground, etc. You then just lay them next to each other to create the world you want. Load that up in the game and there you go! You got a world! Easy eh?

I’ll explain a bit more! I’ll create two tiles now, one for a sky and another for green ground:

image image

Simple and so not pretty, but will have to do. To create a world that has a sky and a green ground, I can just tile the green ones next to each other to form the ground, then the blue ones to form the sky:

image

See? A perfectly ugly world but a world nonetheless! All by having only two tiles and just placing them on a grid (this one is a 10×10 grid by the way). So to create such a world in code, you would load up those two textures and then using a loop, position them next to each other in the order required to show your world. We’ll get to the code later though.

The Tools!

So how do you design such a world anyway? Surely you didn’t think I would suggest that you would do it via code! You need a designer! I’ve done some research and found a really cool tool that you can use to create such worlds very easily! The tool is called Tile Studio. It’s open source and free and works really well.

Let’s dive right in and see how we can use it to create my ugly world above, shall we?

Launch up the app! You should be presented with this window:

image

The first thing you want to do is create a couple of tiles that you can use to draw your world with. Right off the bat, the application will be in tile edit mode and you have a new tile ready to be created right there. So I’ll create a blue tile first:

Pick the Flood Fill tool

image

then pick the color you want to use from the color picker on the right. Then click on the gray tile in the middle of the editor to fill it with that color. Mine looks like this:

image

Now we do the same thing but for a ground tile which will be green. But first we add a new tile by hitting Ctrl+N (or via the menu Tile->Add New Tile). You’ll get another Gray blank tile to work with. Pick the green color and fill it in.

If you look at the bottom left corner of the editor, you should see all the tiles you have created at the moment lined up next to each other in a horizontal strip:

image

Cool! We got ourselves two tiles to work with. Now let’s create a world! To do that, you need to create a new map. Click on the New Map button on the toolbar:

image

When you click on it, you’ll get the New Map window asking you what size should the map be in tiles:

image

I gave it a name, Level1, and set it to be 10 by 10 tiles large. I wouldn’t worry too much about the size now, you can add rows/columns later easily. This is what the map editor looks like:

image

A nice blank map for us to use! To draw on it, you just click on one of the tiles at the bottom left corner of the editor and click anywhere on the map to place that tile there. I started with the ground:

image

and then did the same with the sky to get to the final world:

image

Awesome! We created a world!! Take a few moments to enjoy that fact before you realize “oh…now what?! how do I get this in my game!”. Don’t sweat it… I got you covered!

Exporting the Map

Up to this point, figuring out how to use this editor was a piece of cake! Getting to know how to export the world though, that took some time. But I am here to save you the hassle. Usually the way tile maps are exported is in the form of a number array. Let me explain.

First thing you would do is give indices to the tiles in your tile strip. The tile strip that will be generated by our example looks like this:

image

So the first tile would be index 0 and the next one index 1.

Then the map itself is just an 10×10 array of integers that shows where each tile is placed. Would look roughly like this:

0 0 0 0

0 0 0 0

0 0 0 0

1 1 1 1

1 1 1 1

This makes it easy to use code to loop through the array, and draw the correct tile by referencing the index. So how do we generate something like this for our map?

I expected tile studio to generate something like this automatically, but turns out that they wanted to be very flexible so instead, they gave you a Tile Definition Language (TSD) that you can use to tell Tile Studio how to format the output. Long story short, I wrote a small script in TSD to output a map in XML for easy parsing :)

Download the script from here (xml.tsd).

Take the file you just downloaded and copy it in the folder that contains the TS.exe (Tile studio application’s folder).

Now go back to Tile studio and let’s export the map:

  • First we save the project by clicking File->Save. Save it in a folder of its own.
  • Click on Code-Code Generation Settings

image

  • Pick the xml option for the list as shown (that’s the TSD file we just copied there). Then hit Ok.
  • Make sure that the output is going to be generated in the project’s folder:
  • image
  • Now you’re ready to generate the code! Hit F10 or do it through the above menu.

Tada! Map data generated! Go look in your project’s folder, mine looks like this:

  • image

As you can see, we have a file called Tiles1.xml and a folder called Content which has one image in it called Tiles1.bmp which is a vertical image strip of all the tiles you have.

Let’s take a quick look at the Tiles1.xml file that was created:

image

See what it looks like? Just some simple XML that defines every tile on the map by it’s X and Y positions and which tile it uses. First <MapTile> node for instance has the first tile at position X=0 and Y=0 and uses TileNumber=1.

Note: TileNumber is not Zero based! That means tile number 1 is TileNumber 1. So in my code, when I load this data, I subtract 1 from the value of TileNumber so that it’s zero based which makes life easier. There was no way to have it export this data in Zero based format I am afraid.

Also note that the root element of the map (<map>) includes all the data you need to properly render this map. You have the Width and Height of the grid in tiles, the width and height in pixels of the tiles and the name of the tilestrip file in the Content folder.

Ignore the MapCode attribute for the moment, we’ll get to that later :)

There! We now have a map all drawn up and ready to be consumed by our code! That… will be the topic of my next post! This one was long enough as it is. In the meantime, go mess around with the editor!

Learn 3D and stuff!

July 19th, 2008

Hey guys! Quick post as I am on my way out to the airport for a quick family trip. Check out the 3D Beginner’s guide video tutorial that was just posted on creators.xna.com. It is really neat! It will serve as a really good introduction that I hopefully will follow up myself with some 3D material once I get off my lazy butt and blog some more :/

Have fun!

Template: Game State Management

February 11th, 2008

In my last post in this series, I talked about the GameStateManagement sample. I got a few comments asking that I upgrade it to include the newly threaded Loading.cs that was introduced in the Networking version of the same sample. So, I did that and bundled the whole thing in a template so you can always have it to start new projects with.

The new version of the Game State Management sample now includes a threaded Loading screen that allows you to animate something on the loading portion while your content is loading. I also followed Stephen’s blog post about creating a project template for XNA GS 2.0 to convert it into a usable template (very good read by the way!).

Here’s the template for your downloading pleasure: GameStateManagementWindows.zip

To install it, you need to place it in your ProjectTemplates folder. To find out where that folder is, ask Visual Studio:

  • Click on Tools -> Options
  • Click on Projects and Solutions->General from the tree
  • See where it is? It’s the “project templates location” (second textbox):

image

  • Copy that path and open it in Explorer or whatever.
  • Create a folder under “Visual C#” called “XNA Game Studio 2.0″ and place the zip file you downloaded there:

image

  • That’s it! Now whenever you create a new project, you’ll have this template to start with:

image

Enjoy! Now I’ll start working on my next post ;)

Using the Game State Management Sample

February 4th, 2008

Today we will talk about the next step in my project “Odyssey” game series. We have already talked about why we need to design a game, and then I attempted to design my own game which I call “Odyssey”. Now that we know what we’re trying to build, it’s time to prepare our “workbench” with the tools we need! One of the coolest samples we have released is the Game State Management sample. This sample gives you a working template you can use to create game menus, options, pop up messages, etc. I will be using this sample in project “Odyssey” to handle all the menus and game options. Trust me, this is saving me a whole lot of time! Let’s see how this sample works.

So what does the Game State Management (GSM) sample do exactly? I am going to steal the description text from the sample page on creators.xna.com:

The sample implements a simple game flow with a main menu, an options screen, some actual gameplay, and a pause menu. It displays a loading screen in between the menus and gameplay, and uses a popup message box to confirm whether the user really wants to quit.

I am going to do even better! Here’s a video of what the sample actually looks like, it will give you a much clearer picture of how it works:

See how it works? The sample has all the boiler plate code required to give your game menus, options, pause screen, etc. You just need to figure out how to use it and where to place your game code as well as any customizations to the interface.

GSM Sample Code Structure

The sample is structured in a very object oriented way so that you can just plug into it and get up and running quickly. To start things off, here’s the class diagram of the sample (Click on it to see the full thing):

Class Diagram

Alright, keep this diagram opened in a window since we’ll refer to it quite often.

How does it work?

The basic principle behind the sample is that it manages screens. A screen is a renderable entity in your game. You break down your game into screens and let the ScreenManager manage them for you by bringing them into view and out based on what the player does. Best way to understand how the screens idea works is to go through a scenario step by step.

Let’s go through the scenario of the player booting up the game, they get a Menu screen that has a Play option. They click on that and they see a loading screen and then they see the actual game play. They play a bit and then they hit Esc to quit and are presented with a “Are you sure you want to quit?” message. They say Yes and the game quits back to the main menu. This would require you to break up your scenario into a bunch of screens like this:

So the flow would be:

Menu -> Play game -> Loading Game -> Game play -> Pause Game -> Quit Game option -> Confirm quit -> Back to main menu

The would break up to the following screens:

  • Main Menu Screen: This is the screen that renders the Menu. Here you would have all the code that draws the options, moves selections up and down, etc:

image

  • Loading Screen: This is the screen that renders while the game is loading it’s content. In the sample, it looks like this: (very creative as you can see)
  • image
  • Gameplay Screen: This is the screen that contains all your game play. So if this was say SpaceWar, this would be the screen where the ships fight each other for instance. In the sample, we see this screen:
  • image
  • Pause Screen: When you hit the Esc button, you get to the pause screen which is a screen that renders on top of another one (i.e. Popup). This means that unlike the other screens we saw so far, it doesn’t remove the previous screen but instead dims it and renders over it:
  • image
  • Quit Game Screen: This is the confirmation screen for when you choose the “Quit Game” option. Again, this is a popup screen that renders on top of all the other screens dimming them under it.
  • image

There you go! When you confirm that you do indeed want to quit the game, you go back to the Main Menu screen and you are back at square one :)

Looking at the source

Alright, so now that we somewhat understand how this whole screens thing works, let’s take a closer look at the code. First we’ll start with that layout of the code in source explorer:

image

As you can see, the code is split into two main folders, the ScreenManager and Screens.

ScreenManager folder contains the classes that are instrumental in how the template works:image

GameScreen.cs: This is the base GameScreen class that all your screens will inherit from.  The class has a lot of interesting methods and properties, let’s take a closer look at some of them:

  • bool isPopup: You want to set this to true if you want to have your screen be drawn on top of the current screen. Otherwise, it will be transitioned in as the previous screen is transitioned away. Screens like Pause, confirmation boxes, etc will want this to be true. Screens like the loading screen, game screen, etc will want it false.
  • Timespan transitionOnTime and transitionOffTime: This is how you can control how fast this screen will transition in and out. You want to set this using something like:

this.transitionOffTime = TimeSpan.FromSeconds(2);

  • ExitScreen(): This is the function you want to call when your screen is exiting. This will have it transition off the correct way and get removed from the list of screens to be managed.
  • LoadContent(): Override this function and add code to load any content you will be using in this screen. Do the same for UnloadContent() of course.
  • HandleInput(): You want to override this function in your class and do all the input handling here. Why not do it in the Update? Well, this function will be called when your screen is Active and is in focus. This way the right screen gets to handle the input at the right time.
  • Draw(): Override this function and add your rendering code.

InputState.cs: Helper for reading input from keyboard and gamepad. This class tracks both the imagecurrent and previous state of both input devices, and implements query properties for high level input actions such as “move up through the menu” or “pause the game”.

This class is really helpful and is the one that you should extend to handle your own input as well. The class exposes methods that translate the gamePad input to more appropriate game actions. For instance, things like IsMenuSelect method can be used in the Menu screen to detect if the user clicked on the A button or Enter key to make a selection. Here, check out how it is used in the code for the menus in the sample:

 

 

   1: public override void HandleInput(InputState input)
   2: {
   3:     // Move to the previous menu entry?
   4:     if (input.MenuUp)
   5:     {
   6:         selectedEntry--;
   7:  
   8:         if (selectedEntry < 0)
   9:             selectedEntry = menuEntries.Count - 1;
  10:     } 
  11: }

See how it is very easy to handle input in a meaningful to the game way? No need to do code that directly checks for the A button press, instead, it is wrapped in the InputState class and the action for Menu Select is defined as a check for the A button press. My game will extend this class to handle things like input.MoveShipLeft for instance. Read the source for InputState.cs to get a better idea for how it’s used. Very well commented.

ScreenManager.cs: Ahimage, we come to the mother of all classes! This class right here is the heart of how this sample works!  The screen manager is the component which manages one or more GameScreen instances. It maintains a stack of screens, calls their Update and Draw methods at the appropriate times, and automatically routes input to the topmost active screen (text shameless stolen directly from the source).

So how does it work? Simple. You create your GameScreen drived screens (Menu, game play, pause, etc) and use the AddScreen method to add them to the ScreenManager. The ScreenManager simply iterates over all the screens it had, calls update on each one, calls InputHandle to the top most one and finally renders them all with the top most one rendered last.

So if you add a GamePlay screen followed by a Pause screen and then a Quit Confirmation screen, you’ll get all three screens rendered with the top most one (Confirmation one) in “focus” and the only one handling the input. You RemoveScreen (which you do by calling the ExitScreen() method) the confirmation screen and the Pause screen is now the top most one and is receiving input.

See how it all works now? It’s a stack of screens that are basically layers. Top most layer gets input and the rest don’t. Brilliant!

Every GameScreen has a ScreenManager property on it pointing to the one and only ScreenManager that was created at the start of the game. This way you can add/remove screens to it from any screen in the game.

Tip: Notice the SpriteBatch property on the ScreenManager? That is put there for convenience. Makes is easy to share one SpriteBatch across your game. You won’t need to create a new one in your screen to draw something. Just use this one instead!

 

Now we move on to the Screens folder to see what’s in there. imageThis folder contains the actual implementation of the sample around the template mechanics we discussed above. As you can see, there are a few screens here. There are a few that are specially interesting to us:

  • GamePlayScreen.cs: This is the screen that the sample uses to render the “game play” portion. So if you want to instantly use this sample for your game, just move your game code in this file and hook it up appropriately. It will just work and all you need to do is customize the menus and stuff and you’re done!
  • LoadingScreen.cs: Alright, this one is very important and needs you to pay attention to how it works because it’s a bit different than the others. The purpose of the LoadingScreen is to handle transitions between the game and the menu system. That does not include the menus that popup during the game play though. Let me explain further. When you start the sample, you start by adding a Background screen and then a Main Menu screen. Once you are ready to start the game, you technically can just add the GamePlay screen to the ScreenManager and it will work. But this will mean that you will have both the background and menu screens sitting in memory for no reason. So instead, you use the LoadingScreen as follows:

LoadingScreen.Load(ScreenManager, true, new GameplayScreen());

What this will do is the following: It will first clear all the screens that are in the ScreenManager because we don’t need to worry about them anymore. It then will render a Loading screen image as the GamePlayScreen is loading its content. You don’t have to do anything special for that. The Loading screen will keep the Loading text or image you specify up on the screen until your content is loaded. Very nifty. If your GamePlayScreen’s content loading is very fast, you can disable the rendering of a Loading text by setting the second argument in the Load method to false.

Now, once your game is ready to go back to the main menu screen, you will realize that that screen is no longer there! We cleared it when we loaded the game. So to go back to that screen, the sample uses the LoadingScreen again to transition us back to the Menu system like this:

LoadingScreen.Load(ScreenManager, false, new BackgroundScreen(),
                                                                     new MainMenuScreen());

See how that worked? We are telling the LoadingScreen to clear the current ScreenManager (it does that in the Load method) and then load it up with the BackgroundScreen followed by the MainMenuScreen. We use false for the second argument since we know that our MainMenuScreen loads pretty fast.

So as you can see, the LoadingScreen is instrumental as it sits in between your Main Menu and the game. You use it to transition from one to the other and back. You don’t have to use it and can just stack screens in the ScreenManager, but then if you have a particularly beefy Main Menu screen, you’ll have those resources in memory for no reason. Use it!

As for the rest of the classes up there, take a look at MessageBoxScreen for instance to see how it uses the this.isPopup = true to indicate that it is a pop up window that will not transition the ones below it.

Oh, you should check out MainMenuScreen.cs and OptionMenuScreen.cs to see how they use MenuEntry class to implement the actual menu items. It uses events to detect when a menu was clicked. It’s simple enough to understand from the code.

Final words and next steps

Phew! That was a loooong post eh? Sorry about that but I really felt like I needed to make sure that this sample is fully explained before we can proceed. I myself haven’t really used it in depth, so this was a good exercise for me too. Once you go through how it works and look at the code a little bit, it totally makes sense very quickly and becomes trivial to use. It is intimidating at first but hopefully my explanation will help remove that.

Going forward we’ll start thinking about how to implement and structure project “Odyssey” in preparation for the implementation phase! Looks like I will have to actually code up this game! Should be fun and educational too!

In the meantime, go ahead and download the game state sample now and start playing with it. Get a sample game or even a moving texture integrated in it (Tip: Put the code you already have in the GamePlayScreen.cs file for starters). You will learn to love this sample quickly.

Project "Odyssey", The Design

January 29th, 2008

imageAs promised in my previous post, today I’ll try to take a stab at designing my own game. I told you  how important the game design process is and how you should know all that there is to know about your game before writing any code. Well, turns out that it’s not a very easy thing to do! I spent a few days brainstorming in my head and trying to come up with what I wanted to do. Finally, I got a good grasp on the major game mechanics I wanted to do and started to dig deeper and find more ideas. Here’s what I’ve come up with so far.

Project Name

If recall from the last post, I said that it’s pretty important to come up with a project name for your game. For me, I picked the name “Odyssey”! Why do you ask? I don’t know… it’s all I could come up with. I didn’t say it had to be a good name! Just that you should have one! Mine’s lame, but I am gonna stick with it!

Game Description

Odyssey is planned to be a 2D side scrolling shooter that is pretty simple. In one player mode, you play as a flying ship (how original! I know) with enemies attacking you from the right side of the screen.

In two player mode the game really shines! The second player controls a tank on the ground and both players work together to fight the enemies. Each player has a dominant color (indicated by the color of their ship/tank). Enemies that carry your color only you can kill, while other enemies you can’t harm. This leads to a game play where the two players have to work together to eliminate the correct colored enemies otherwise they will both die by an overwhelming force. Enemies not of your color will attempt to attack you more frequently and thus cause a great threat to you that can only be eliminated by your buddy.

In two player mode, the ship can move up/down/left and right while the tank can only move left and right. The ship has less health than the tank as well as less firepower. But the agility/speed it can move with offsets that weakness.

The game will progress via levels. Each level will have a preset number and type of enemies that will attack you ending with some sort of boss battle. Boss battles will utilize the same color based combat, details will differ per boss. You win the game if you finish all the levels. You lose when you consume all the available lives you have. In two player mode, you and your buddy share the same pool of lives, so you both lose when you both consume them all.

The enemies will come in different flavors:

  • Neutral color enemies: These guys can be damaged by either player. They are the only type that is available in the single player mode.
  • Color matching enemies: These enemies match either of the two players’ color. They can only be killed by the correct player. They will attack the non-matching player more frequently and hence cause a threat to them. These are only available in two player mode.
  • Boss: Bosses occur once per level at the end. They are unique per level and need a strategy to beat them.

You have a pool of lives in the game, once you go through them all, you are dead and the game is over. Two player mode both players share the same pool. Players gain an extra life everytime they score 5000 points (might change that based on how the game plays, might increase or decrease it).

The game will have power-ups in multiple flavors. Power-ups are spawned based on certain triggers from dead enemies:

  • Health: These will start first floating in the air for 2 seconds to give the ship a chance to get them then will drop on the ground for the tank and stay for 2 seconds before they disappear. These will spawn after you kill X number of enemies. X is to be determined.
  • Weapon Fire Rate increase: This power up will increase the firing rate of your weapon. It will spawn and start to float downwards towards the floor. Will live on the floor for 3 secs then disappear. Either player can pick it up. Will spawn after you kill X enemies and will last for 20 seconds indicated by a timer on the HUD.
  • Nuke power-up: This power-up will drop randomly and allow you to detonate a nuke that clears all enemies on the screen.

Odyssey might have an achievement system. This is yet to be determined. If it does, it will be based on number of kills, length of time you survived, etc.

Network play is a possibility based on time and cost needed to implement it. Same console/PC play remains as priority 1 for now.

Game will support Xbox and PC and use keyboard/controller.

Game Story

The game will not really have much of a story. Your basic alien bad guys attacking our planet and we have two new war machines in the form of a ship and tank that work together to fend off the attacks. I might re-think the story later as I get more of the game mechanics nailed down.

Inspirations

The game is inspired by a lot of games out there. The first one that comes to mind is Heavy Weapon on Xbox Live Arcade. I like the way the tanks in that game move around and the way the enemies attack. Here’s a screenshot of Heavy Weapon for reference:

image

Things I like:

  • I like how the tanks move horizontally from that game. I will use that same motion in Odyssey.
  • I like the coloring of the tanks to differentiate them. This is basically a Color.Blue argument to spriteBatch that tints the color of the sprite. I will use that same method in Odyssey two player mode.
  • I might borrow some of the weapon ideas from here too.

Another game I looked at is Jet’n'Guns seen here:

image

I particularly like the HUD in this game. Check out how the health is indicated by the small gauge at the bottom left corner. Simple HUD, and very non-obtrusive. The graphics are cool as well, not that I expect to get anywhere close to that kind of work ;)

Experimental Ideas

I have this one idea that I am experimenting with in my mind because I am not sure how well it will work. The game will inevitably reach a point where one of the players has more health than the other one and wants to help them out. I am thinking of integrating an ability that sits on a long cooldown timer that allows you to transfer some of your health to your buddy to help them out. You lose that health of course, but you give them the boost they need to stay in the game and not consume a life. Still thinking about that one though.

So what’s next?

So now that I have a basic idea of what I want Odyssey to look and play like, I will start to think about what technologies and techniques I want to use for the game. Next post, we’ll talk about a very popular and heavily used sample that I plan to use for this game. I am talking about the GameState Management sample that you can grab from http://creators.xna.com. It’ll be a good idea to take a look at it now and be familiar with it in preparation for next post!

Game Design: Let’s make a game!!

January 23rd, 2008

This is the first post in my “Building a game” series! The aim of this series is to walk through building a game from scratch and try to include as much of the thought process involved as possible. So how about you grab yourself something to drink and let’s sit and chat about game design!

Before I sat down to write this post, I walked to Shawn Hargreaves and Eli Tayrien’s office and talked about game design with them. These guys know a whole lot when it comes to game development and I highly value their input. The question I asked was “How does one go about designing a game?”

There are two different aspects of game design that you want to think about: Game play mechanics and Game architecture. One has to do with how the game will play while the other is about how the game code/engine will work. For this post, we’ll talk about game play mechanics. These are the sort of things that you really need to have nailed down before you write a single line of code. The reason you want to flesh all that stuff out early on is to avoid being halfway through developing the game and then realizing that you really want to add this awesome new game concept. Knowing something like that late in the cycle will probably cause you a lot of pain to get it to fit in. Take your time now, think about stuff early on and get your blue print drafted out.

Project Name

This is the first thing in my opinion that you should come up with. Every project needs a name, and your game is no exception. A project name is not the final name of your game though. I mean, it can be if you want, but most of the time it isn’t. Windows Vista was called Project “Longhorn” for instance. XNA Game Studio v1.0 was “Rogue” while v2.0 was “Shaman” (Yeah… I know what you’re thinking…).

So why is a project name important anyway? Because it gives your project an entity. If you cared enough to name it, then you probably will care enough to finish it. Once an entity gets a name, it starts to get somewhat of a virtual soul. You refer to it by name, you talk about it as if it exists. Plus, depending on your project name, it can make it sound very cool and top secret-ish vs geeky and nerdy like our project names.

So go ahead, name your project something cool! It’s step #1 in the fun.

Game Description

This is a very important step in game design. This is the overall description of what your game is all about. Start with the idea you have for how it will play and then add to it. Someone reading this should be able to know everything about your game without playing it. It’s almost like writing the manual for the game before the game is written. So what kind of things do you want to think about for your game description? Let’s list some out:

  • What is the game play about? Is it about a player controlling some entity in the world and shooting enemies? Is it a puzzle like game where you have to solve a puzzle of some sort?
  • Is your game single player or multi-player? If it is multi-player, is it co-op or competitive? How are players going to interact together? Will I have to kill my opponent or work with them by sharing powers and/or resurcting them when they die?
  • Is your game’s progression based on levels or increasing difficulty? If you’ll have levels, how will they be different from each other? Will levels introduce different challenges to the player or just provide a backdrop?
  • What kind of behavior will my enemies have? Will they be coming at me in waves? Will they shoot at me and if so, how accurately? Will they have varying movement speeds? like some will travel fast while others slow?
  • If you’ll have weapons, how will they work? Are they upgradable? if yes, then how? Are they balanced? Can you carry more than one kind of weapon?
  • How will the player achieve victory or defeat in your game? Do I win if I kill everything on the screen? Do I lose if I take too long to finish a level? How can you make it very clear to the player that they are winning vs losing?
  • Do I have power-ups in the game? How do I get them? What do they do? Are there power-downs? as in items that if I pick them up they actually hurt me?
  • How does scoring work in the game?
  • What happens when I die or lose? Do I have the concept of “lives”? Do I start from the beginning or can I continue from where I died?
  • Will my game have network play?
  • Will the game have some sort of achievement system? How will that work?
  • How will the controls of the game work? If the game is PC/Xbox, then how can you make sure one platform doesn’t have an advantage over the other due to controls? It might be ok to have that, but it’s a decision to be made.

Game Story

So what about the game story! The world where my game is set in? I have this awesome story about an evil alien race that is determined to wipe humanity out by seeking ring like structures left by an ancient advanced race that is long gone! But wait! There’s a twist, there’s another alien race that will start messing with BOTH the humans and the evil aliens!

Yeah… there is a reason that I put game story after game design. According to Shawn Hagreaves, you can spot a good game designer from a bad one by focus on game story first. In the real world of game development, it is very possible that your sci-fi based game will be changed to a Viva Piniata like game by the publisher if they feel the game play mechanic works and the market needs such a game type now vs sci-fi.

Having a good game story is important and all, but make it a priority 2 while game play mechanics a priority 1. It doesn’t help if you have an awesome story but once the game starts, the player is bored out of their mind. While it is possible – and happens quite often – that a game with a pretty poor story and world but has amazing game play will win in the end. Having both story and gameplay being equally good is the holy grail of game development I guess. Some examples exist, but not many.

Stand on those shoulders damn it!

See those giants? Stand on their shoulders! Once you identify what kind of game you want to make, it is very helpful to go out there and find similar games. Play them. Take notes. Have fun. Spend a lot of time criticizing them and reading what others said about them. Find things that you like about them vs things you don’t like.

For instance, let’s say you’ll be creating a Real Time Strategy (RTS) game. Go out there and find what others have done with RTS games. You’ll find that they can be quite different. Some games like Warcraft 3 have the whole Hero RPG element in the game. Some people love that while others hate it. Some RTS games have very different races to play with like Starcraft. What kind of destructive super powers did you like? What elements seemed really fun while others were meh. Resource management in RTS games can be very different. Some have you gather one or more kinds of resources. Others make you hold points on the map to gain resources.

The point is, see what’s out there and learn from it. It’s not about copying what others have done, it’s about improving and adding your own touch to already successful ideas. It’s a delicate balance between improving upon vs flat out copying. Don’t worry though, if you do copy something, people playing your game will let you know very quickly :)

It’s the little things

This is the trickiest part of game design if you ask me. There are games that do this very well. You’d be playing a game and something very small and seemingly insignificant would happen that would make you feel so good! It’s kind of hard to explain without an example.

Take Call of Duty 4 for instance. One of my favorite games right now. I noticed that one of the things that I LOVE about it and actually makes me want to play it more is the feeling it gives you when you shoot an enemy. It’s a mixture of the way the aiming reticule changes to an X indicating that you are hitting an enemy and that awesome DUB DUB sound it makes when you’ve landed a killing blow. The experience points that show up as well seal the deal. Check out what it looks like:

Call of Duty 4 aiming reticule

I don’t know what about this whole experience that makes every kill in CoD4 very enjoyable. You feel you’ve done something! You’ve made a change. Now how do you think something like that sounded on paper?!

CoD4 Design team: “Yeah… so we want the aiming reticule to change to a X when you’re hitting a person. We also want to have this like… eh… DDDUB DDUB sound play as your bullets hit the target. It’ll be awesome!!!”

Dude with $$$ (i.e. Publisher): “Yyyeah… that sounds… like a lot of fun. What else you got?”

Stuff like that are pretty hard to come up with. But it’s better to think about them and try to come up with some than to not at all. Think about how you can make your player feel good when they do the right thing. Prototype such ideas even if on paper. Believe me, once you find that little hook, you’ll be very happy.

Here’s another example for you, I am just so full of them today :) We had a game internally developed by some dude from Rare studios while we were working on version 1.0 of XNA Game Studio. The game just couldn’t be simpler than it was. You and up to 3 other people control 2D ships on the screen and you all have to work together to destroy all the asteroids on the screen. Every level, you have to destroy more asteroids. The hook though was when one of your buddies died. You can bring them back to life if you collect a randomly spawning star that is the same color as their ship. Once your buddy would die, they would instantly start yelling “BRING ME BACK!!! QUICK!!” and everyone would be searching all over the screen waiting for their resurrection star to show up. Once it did, we would ALL rush to it to bring them back and more often than not, we’d all ram into an asteroid and die together. Such a simple concept but it was so fun that we played that game for hours! Probably caused us to delay the release a little bit ;)

Last words

Spend the time doing all this for real. Get yourself some sort of notebook or something, write the project name on it and write down all the ideas you have. Flesh them out, discuss them with others or teammates. Criticize them, find the gaps, find the fun stuff, etc. Before you start coding your game, you should know everything there is to know about it. This way you won’t be slamming your head on a wall later because your design is not flexible enough to add that awesome feature you just thought of.

Next post we’ll actually go through the exercise of me putting all this into practice as I design what will probably be a super lame game :) It’ll get the point across though. In the meantime, start thinking about your game!

When Things Collide, We Detect!

January 2nd, 2008

Starting off 2008 with some collision detection! Now that we’ve slowly learned how to work with XNA framework, we’re getting very close to knowing most of what we need to build an actual playable – and maybe even a fun – game. Let’s get right to it then: What is collision detection?

Collision detection is one of the methods you can use to detect if two objects in your game collide. Why would you want to do that? Let’s say you have a very simple game where the player controls a ship that shoots missiles. You have enemies that fly around and you shoot at them. How will you know when your missiles hit an enemy? That’s where collision detection comes into play. You want to detect when two objects – missiles and enemy ship – collide together.

How does collision detection work? Here’s the “theory” behind it. Check out this diagram here:

image

See how we have two rectangles? Obj 1 and Obj 2. Right now they have not collided together, right? Let’s see what happens when they do collide:

image

See that? The rectangles have collided and we can see that due to the intersection that happened between them. This is how you can detect if two rectangles have collided together: if they intersect together.

So how do that apply to a game? What you need to do is specify a rectangle for every object in your game that contains that object. Such a rectangle is called a BoundingRectangle. As objects in the world move around, you check for collisions at every Update call to see if the rectangles intersect, if they do, you got a hit!

Visual example:

image

See how we have a virtual rectangle drawn around each texture in the game? They are not actually rendered of course, just defined in the code and kept around for collision detection. If these two creatures actually collide, the rectangles are going to intersect and we get a hit.

Show me the code!

Let’s have a quick look at how this would work in code. We’ll have a very simple scenario where you have an enemy and a missile that is aimed at them. We want to know when the missile hits the enemy so that we can render an explosion or something cool.

First we see what data structures we need to create:

 

   1: Texture2D enemy;
   2: Texture2D missile;
   3:
   4: Rectangle enemyBR;
   5: Rectangle missileBR;
   6:
   7: Vector2 enemyPosition;
   8: Vector2 missilePosition;
  • Lines 1 & 2: Simple declaration of the enemy and missile textures we’ll use.
  • Lines 4 & 5: These are the two Bounding Rectangles we’ll use for collision detection. One for the enemy and one for the missile. We use the Rectangle structure from XNA framework for this.
  • Lines 7 & 8: Two Vector2 objects that we’ll use to track the position of the enemy and missile in the world.

Next we initialize everything, I did that in my LoadContent method:

 

   1: protected override void LoadContent()
   2: {
   3:     spriteBatch = new SpriteBatch(GraphicsDevice);
   4:     enemy = Content.Load<Texture2D>("enemy");
   5:     missile = Content.Load<Texture2D>("missile");
   6:
   7:     // Init positions
   8:     enemyPosition = new Vector2(10, 10);
   9:     missilePosition = new Vector2(70, 70);
  10:
  11:     // Init Bounding Rectangles
  12:     enemyBR = new Rectangle((int)enemyPosition.X,(int)enemyPosition.Y,
  13:                                 enemy.Width, enemy.Height);
  14:     missileBR = new Rectangle((int)missilePosition.X, (int)missilePosition.Y,
  15:                                 missile.Width, missile.Height);
  16: }
  • Lines 8 & 9: Nothing new here, just initializing the positions of the enemy and missile in our world. I just put whatever values in there, they are not really accurate ;)
  • Lines 12-15: We initialize the Bounding Rectangles. The constructor for the Rectangle struct takes a position in X,Y and a Width and Height values. I use the initial positions of each object for the X,Y and the Width and Height of the texture for the rest. Very simple.

Finally, we go to 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:     // Move stuff around based on input or whatever
   8:     // I removed that part of the code for simplicity
   9:
  10:     // Make sure to sync the Bounding Rectangles with the current position
  11:     // of the contained object
  12:     enemyBR.X = (int)enemyPosition.X;
  13:     enemyBR.Y = (int)enemyPosition.Y;
  14:
  15:     missileBR.X = (int)missilePosition.X;
  16:     missileBR.Y = (int)missilePosition.Y;
  17:
  18:     // Now check if they collide or not
  19:     if (enemyBR.Intersects(missileBR))
  20:     {
  21:         // We got a HIT! Do something!     
  22:     }
  23:
  24:     base.Update(gameTime);
  25: }
  • Lines 12-16: As we moved the sprites around the screen based on user input or whatever, we have to make sure we synchronize the Bounding Rectangles as well! They won’t move on their own. So at every update, I make sure to update the X,Y values for the Rectangles.
  • Lines 19-22: This is where the magic happens! We use the Intersects method in the Rectangle struct to see if the enemy rectangle intersects the missile rectangle. If they do, then we know we got a hit!!

That’s it! How easy was that eh? What’s even cooler is that these same concepts pretty much work the same in 3D graphics. But we’re getting ahead of ourselves, we’ll get there soon.

Tips & Tricks

Some food for thought:

As you probably figured out by now, it’ll be easier if you create a container object for your objects in the world that has all the data needed by that object. So things like the texture that represents it, the position in the world, the bounding rectangle, etc. This way you can have everything self update in a more automatic and contained way. Manually updating the bounding rectangles like the code above is not the most efficient way to do things.

When you initialize your bounding rectangles, you don’t have to make them the exact size of the texture like I did above. Actually, most games like to make them smaller so that a collision happens when the two objects rendered are overlapping more than in my example. This way you use the rectangle to mark the “hit-able” part of the image which for a ship might be the power core or something.

Another REALLY cool use of bounding rectangles is to mark areas in the world where you want to know if something enters or exits it. For instance, let’s say you have your ship moving left and right along the X-axis at the bottom of the screen. How do you make sure it doesn’t move off the screen edge? You can keep checking the x-value of the ship against x = 0 (left side) and x = screen width (right side) and make sure you don’t move it beyond those points. OR… you can put small bounding boxes at the right and left of the screen and check for intersections.

Tip conclusion: Bounding rectangles can be used to detect when objects hit areas of the screen! Use that to achieve things such as event triggers or movement restrictions.

Last tip… hmm… I got nothing for you… I just don’t want to end on a “Tip Conclusion” since it kinda looked ugly ;) Maybe you guys have some more tips to share!

Tips from you guys! (Keep them coming!)

From KaBaL: Don’t forget, you can use more then one Bounding Box for a single object (sprite) that way you can get better detail for irregular shaped objects (ship’s nose, wings, tail)

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!