Adding a Background Image

Next, you'll add a little more spice to your game by adding a background image. With the source code for this chapter (again, in the AnimatedSprites\Content\Images folder), you'll find an image named background.jpg. Add the image to the project the same way you added the other images (right-click the Content\Images folder, select Add → Existing Item..., and navigate to the background.jpg image included with the source code).

Your SpriteManager class was built to handle animated sprites and derived classes. Something as simple as a background image can just be added to your Game1 class. You'll need to add a Texture2D variable for the image:

Texture2D backgroundTexture;

and load the Texture2D image in the LoadContent method:

backgroundTexture = Content.Load<Texture2D>(@"Images\background");

Next, you'll need to add the code to draw the image. Because you'll now have multiple sprites being drawn within your Game1 class (the SpriteFont counts as a sprite, so you'll be drawing a score sprite as well as a background sprite), you need to make sure that the score text is always on top of the background image. Typically, when trying to ensure that one sprite is on top of another, you modify the SpriteBatch.Begin call to include an appropriate SpriteSortMode. However, this is a case where you're only drawing two items, and you know that you'll always want to draw the score on top of the background. As such, you can forego the overheard involved in specifying a sort ...

Get Learning XNA 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.