Skip to Main Content
Learning XNA 3.0
book

Learning XNA 3.0

by Aaron Reed
November 2008
Beginner content levelBeginner
510 pages
16h 24m
English
O'Reilly Media, Inc.
Content preview from Learning XNA 3.0

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning XNA 4.0

Learning XNA 4.0

Aaron Reed
Beginning C# 7 Programming with Visual Studio 2017

Beginning C# 7 Programming with Visual Studio 2017

Benjamin Perkins, Jacob Vibe Hammer, Jon D. Reid

Publisher Resources

ISBN: 9780596154905Supplemental ContentErrata Page