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

Creating Sprites at Random Intervals

This chapter picks up with the code that you finished writing in Chapter 6. Open that project and use it throughout this chapter.

You have already created a sprite manager that draws and updates all the sprites in your application. However, right now all you have is a handful of skull ball sprites that are created when the application starts. Even worse, those sprites don’t move—they just sit there and animate. That just isn’t going to cut it; you need some action and excitement in this game. In this section, you’ll add some code that will create automated sprites at random intervals and send them flying onto the screen to force the player to move around and work a little to avoid hitting them.

Rather than creating the objects in waves or all at once, you want to create them at random intervals. This adds a bit of variety to the game and also serves to keep the player guessing. The first thing you need to do is create some variables that will help you define how often to create your automated sprites.

First, to handle the random factor in your game, create the following variable at the class level in your Game1 class:

public Random rnd { get; private set;}

Then, initialize the Random object in the constructor of the Game1 class:

rnd = new Random(  );

You now have a Random variable that you’ll use for all random aspects of your game. When using random number generators, it’s important to make sure that you don’t create multiple random number generators ...

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