Learn 3D and stuff!

Posted in Beginner Game Tutorials on July 19th, 2008 by nazeeh

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

Posted in Beginner Game Tutorials on February 11th, 2008 by nazeeh

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

Posted in Beginner Game Tutorials on February 4th, 2008 by nazeeh

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

Posted in Beginner Game Tutorials on January 29th, 2008 by nazeeh

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!!

Posted in Beginner Game Tutorials on January 23rd, 2008 by nazeeh

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!

Posted in Beginner Game Tutorials on January 2nd, 2008 by nazeeh

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!

Posted in Beginner Game Tutorials on December 19th, 2007 by nazeeh

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!

Posted in Beginner Game Tutorials on December 18th, 2007 by nazeeh

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 1680×1050
   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();