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 ...
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.