Balanced Waves and Random Weight Values

Blake Zoeckler
3 min readJun 8, 2021

--

Objective: Create a balanced spawning system between enemies and pickups. Pickups like health should be rare, while ammo is frequent.

Today we’ll be looking at how to better control the frequency of certain enemies and powerups as they appear in the game. Right now we just have a free-for-all of different enemies and powerups randomly appearing.

SpawnManager.SpawnPowerupRoutine
Inside of SpawnManager.WaveSpawnRoutine, which creates the enemies.

Note that both get a random index between 0 and the length of their respective arrays, so any given type of enemy or powerup has an equal chance of being picked.

We’d rather be able to control how likely it is for each kind of enemy or powerup to be created. That’s why we should introduce a weighted chance to each powerup or enemy.

New interface that Enemy and Powerup will implement
New Enemy and Powerup variable and public getter method

The idea is we can control the frequency of the enemies and powerups appearing based on the spawn chance weight. In this case, the ammo powerup, with it’s weight of 15, will appear five times as often as a missile powerup that has a weight of 3.

Now we can make use of these weights using a clever algorithm. We find the total weights of all the objects, then get a random integer number between 0 and the total weight. We then check each object again one at a time to see if random is less than its weight, and pick that object if it is. Otherwise, we reduce the random value and try again until we find an item. Objects with higher weights are much more likely to be picked, since it’s more likely that random will be less than that weight.

Now we can use this helper method for both enemies and powerups, since they are both GameObjects that use the ISpawnChanceWeight interface.

Edited SpawnManager.WaveSpawnRoutine

Testing if this works is a little tricky, since it can be difficult to judge if things are appearing at the right frequency according to the weights. What we can do is make a editor-only “cheat” that’s capable of creating a lot of powerups at once.

SpawnManager.Update

Now to test the new random weighting, we can just start the game and hit ‘P’ a bunch of times.

I tried it several times and generally got results like this, where Ammo is the most frequent powerup while Missile and Repair are significantly more rare. That’s just like we wanted, so we can call this a success!

--

--

Blake Zoeckler
Blake Zoeckler

Written by Blake Zoeckler

I’m a passionate and talented software engineer seeking an opportunity in game development.

No responses yet