O'Reilly logo

Learning XNA 4.0 by Aaron Reed

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Coding the SpriteManager

Although your SpriteManager class is wired up and functional, it doesn’t do anything yet. You can draw in your SpriteManager’s Draw method, just as you can in your Game1 class. In fact, to clearly separate the sprite logic from the rest of your game, you’ll want the SpriteManager to actually control all drawing of sprites. To accomplish that, you’re going to have to add some code that will draw your sprites to that class.

The first thing you’ll need is a SpriteBatch. Although you already have a SpriteBatch object in your Game1 class, it makes more sense to create your own here for use within this class than to reuse that one. Only that way will you be able to truly isolate and modularize your game component code. Too much passing of data back and forth between the game and the game component will break that model.

In addition to adding a SpriteBatch variable, you need to add a few other variables: a list of Sprite objects that will hold all the automated sprites and an object of type UserControlledSprite that will represent the player. Add each of these variables at the class level inside your SpriteManager class:

SpriteBatch spriteBatch;
UserControlledSprite player;
List<Sprite> spriteList = new List<Sprite>(  );

Just as the SpriteManager’s Update and Draw methods are wired up to be called after your Game1 class’s Update and Draw methods are called, the Initialize and LoadContent methods will also be called after the equivalent Game1 methods. You’re going to ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required