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

Randomly Spawning Sprites

All right, let’s spawn some sprites. You want to make your sprites spawn at somewhat random intervals, and you want them to spawn from the top, left, right, and bottom sides of the screen. For now, you’ll just have them traveling in a straight direction across the screen, but they’ll do so at varying speeds.

You need to let your SpriteManager class know when to spawn the next enemy sprite. Create a class-level variable in your SpriteManager class to store a value indicating the next spawn time:

int nextSpawnTime = 0;

Next, you need to initialize the variable to your next spawn time. Create a separate method that will set the next spawn time to some value between the spawn time thresholds represented by the class-level variables you defined previously in the SpriteManager class:

private void ResetSpawnTime(  )
{
    nextSpawnTime = ((Game1)Game).rnd.Next(
        enemySpawnMinMilliseconds,
        enemySpawnMaxMilliseconds);
}

You’ll then need to call your new ResetSpawnTime method from the Initialize method of your SpriteManager class, so the variable is initialized when the game starts. Add the following line at the end of the Initialize method of the SpriteManager class, just before the call to base.Initialize:

ResetSpawnTime(  );

Now you need to use the GameTime variable in the SpriteManager’s Update method to determine when it’s time to spawn a new enemy. Add this code to the beginning of the Update method:

nextSpawnTime −= gameTime.ElapsedGameTime.Milliseconds; if (nextSpawnTime ...

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