UserBruiser
UserBruiser

Reputation: 155

Randomly spawning enemies XNA 4.0 (WP7)

I am creating a 2d side scrolling(kinda) game for the windows phone in C# and XNA.

I have a character animation that makes it look like the sprite is moving, however the background and enemies are the only things moving. I have loaded the texture for the enemy and the position on the screen is static so that's fine. But my problem is, I want to spawn these enemies at random intervals. I have set up a random number generator, an int and a couple TimeSpan variables.

Here is the code I have placed in the UpdateEnemies method.

Note: in Update, I am calling UpdateEnemies(gameTime);

random = new Random();
spawnSeconds = random.Next(1, 6);
enemySpawnTime = TimeSpan.FromSeconds(spawnSeconds); 
if (gameTime.TotalGameTime - previousSpawnTime > enemySpawnTime)
{
    previousSpawnTime = gameTime.TotalGameTime;
    // Add an Enemy
    AddEnemy();
}

I am having an issue here as the enemies spawning is not random. They spawn at the same interval for that particular run.

I have used Breakpoints and the spawnSeconds and enemySpawnTime update fine everytime but still this issue.

Any help would be greatly appreciated.

Upvotes: 1

Views: 3397

Answers (2)

Asik
Asik

Reputation: 22133

Assuming UpdateEnemies is called on every Update(), you are changing enemySpawnTime on every Update(), which doesn't make sense. You should only change it when an enemy spawns, i.e.:

if (gameTime.TotalGameTime - previousSpawnTime > enemySpawnTime)
{
    // Add an Enemy
    AddEnemy();

    // Update the time left next enemy spawn
    previousSpawnTime = gameTime.TotalGameTime;
    var spawnSeconds = random.Next(1, 6); // random should be a member of the class
    enemySpawnTime = TimeSpan.FromSeconds(spawnSeconds); 
}

And as noted previously, only create the Random() object once, for example in Initialize(), and make it a member of the class.

Upvotes: 2

jgallant
jgallant

Reputation: 11273

random = new Random();

You are creating a new instance of Random every single time you call your update function. Doing this will cause your random function to generate the same value, since it will be based off the same seed.

Instantiate your Random object outside of your Update function, possibly in your constructor. Doing this will improve your code, as well as fix your issue.

Upvotes: 2

Related Questions