Thursday, February 08, 2007

A general GameScreen implementation

A few weeks ago, Eli posted a design for a GameScreen and a GameScreenManager to use in XNA. The GameScreen is a base class, like Game, that implements one layer of a game (e.g. the game itself, or a menu, or a title screen). The GameScreenManager is used by the Game class to switch between these screens using a stack-based design. I ended up implementing this design for my book, and I've been using a few weeks with no problems so I thought I'd post it here for the XNA community to use. To use the GameScreenManager, declare a public instance of it on your Game object, along with any screens that are spawned by Game and not by other screens. public GameScreenManager screenManager; // Screens StartMenuScreen menuscreen; PlayScreen play; public Game1() {

... screenManager = new GameScreenManager(2); ...
} Add the first screen during Game.Initialize() by creating the screen, initializing it, and calling GameScreenManager.Push. I also create the other screen at this point, but I don't initialize it until it's invoked. protected override void Initialize() {
// TODO: Add your initialization logic here play = new PlayScreen(this); play.Initialize(); screenManager.Push(play); menuscreen = new StartMenuScreen(this); ...
} At some point later, if the menu is invoked, I initialize it and push it over top of the play screen: // if the menu isn't already up if (screenManager.Peek() != menuscreen) { GamePad.SetVibration(PlayerIndex.One, 0, 0); // install menu screen menuscreen.Initialize(); screenManager.Push(menuscreen); Lastly, when the menu is finished, I fire an event back Game, which removes it. public void MenuScreenFinished(int Selection) {
screenManager.Pop(); if (Selection == 0) return; if (Selection == 1) { play.ResetGame(); } if (Selection == 2) { this.Exit(); }
}
You can download the GameScreen.cs and a sample screen here. Also, I should probably hawk the fact that my book is available for pre-order.

Labels: ,

Thursday, January 04, 2007

How I spent my Christmas Vacation

I've been working feverishly every night and weekend on my book. The first step is to do the code for the second section of the book, that introduces 2D programming concepts. To illustrate sprite programming I've created a game I call "Velocity" where you pilot a spaceship through rings while avoiding asteroids and the treacherous gravity wells of planets. I'm not much of an artist, but here is a screenshot of the game working on the test map (I plan to make one decent map to ship with the book). Click on the graphic for the larger version. I may get a chance to improve the art before the book is finished (Mars and the asteroid Gaspra courtesy of NASA, but the ship and the ring are my fumbling attempt at art). I'm also doing 2 more versions of Velocity: one as a "2.5D" game and one as a 3D game from within the ship's cockpit.

Labels: ,