Monday, September 14, 2009

XNA and Drawable Game Components

XNA has this feature of letting your classes inherit from DrawableGameComponent, or GameComponent. What this inheritance does is let you write your own overridden Draw, Update, Initialize, etc. methods that will be executed during the corresponding base.* call in the main game class.

The overridden Draw, however, does not take a spritebatch, or anything else but gameTime, though. So how do you actually draw anything in those methods? The answer is two-fold:

1. Don't make too many classes that actually draw something. Make more 'master classes' that draw everything contained in them, like maps or menus.
2. Game.Services.GetService

"Game.Services.GetService?" you say, "how does that do anything?" To that I say, "ah, it lets you pull generic services defined on the game!" So when your spriteBatch gets initialized in the main game class:

spriteBatch = new SpriteBatch(GraphicsDevice);

you can add it to the services of the game:

Services.AddService(typeof(SpriteBatch), spriteBatch);

and pull this service from any class:

spriteBatch = (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch));

Just remember to declare your own spriteBatch variable in the subclass, and pull it from the game some point after it's been initialized!

There are very few articles or threads I could find that dealt with this exact problem. Most ranged from either a really simple drawing that occured in the main game Draw(), or more complex drawing that didn't use a spritebatch, at least not on the top level. I finally found an article here that was simple and consice enough for me to decypher what was going on. Props to the author!

No comments:

Post a Comment