Given the original code for a sprite class the source of which is provide here was provided by Neil Gannon.
We need to sub class the class off DrawableGameComponent and then add an override for update and draw. These must be public overrides to match the method declarations in the the DrawableGameComponent Class. The game component needs it’s own sprite batch to draw to the graphics card and hence it needs to see the Games Graphics Device. But thankfully this is exposed in the component model for the game class. The Class becomes
- The constructor has to have a reference to the game that creates it and must pass it on to the Super class.
- We can use this reference in the constructor to access the Graphics device reference to create the sprite batch. We can alternatively access the publicly exposed Game property Game.GraphicsDevice and indeed you can reference the public exposed properties of the Game class from anywhere in the game components.
- You must remember to add the created sprites as components in the Game class when we create the sprite
Now we can subclass the Sprite Class and create two different types of Sprite game components. The player Sprite class will have an update method that will override the sprite update and deal with the input from the input device and the CGC Sprite Class will move around the screen.
We’ll look at those classes next time.
It’s worth looking at the forum discussion here about the ins and outs of using multiple sprite batches or a single sprite batch for drawing components. So it would seem from the comments made by Shaun Hargreaves in the forum discussion referenced above that although components give good modularity and structure to games, but at the cost of efficiency in committing to the graphics device as multiple sprite batches in components seem not to be a good idea from a performance perspective!! So for multiple instances a Drawable game component may not be a good idea?? So back to the drawing board eh? It would be a good idea to change the XNA framework so that it batches sprite batch (yeah I know – a bit of a recursive definition) and have a common end() method for them. The solution suggested is to have a Sprite Manager. But I thought that’s what a sprite batch should do!!
At that stage we might consider making the Sprite Class abstract as we would probably not want to create instances of it after that subclass action.