Project 1: Space Shooter
How to balance the spawning
Introducing a variation of roulette wheel selection
Now that the wave spawning is done, it is time to consider the actual spawning. Thus far all the enemies and the power ups have been spawned with an equal probability. Upside of this is that more powerful power ups spawn as likely as the lesser ones, downside being that the harder enemies have also spawned as likely as the easier ones.
For these reasons, and many more, it is time to balance things out by introducing a roulette wheel selector to select what will be spawned. The selector uses weights and a sum of the weights as basis for the selection.
The weights themselves don’t have to sum up to hundred or one, either one is needed when the algorithm deals with probabilities, instead the weights can be free and sum up to any number. This will be beneficial when new objects are added, because there is no need to change the weights, or in that case the probabilities, of the pre-existing objects to make the sum equal of either one or hundred.
As for the weights themselves, higher the value the more likely it is for the corresponding object to be selected. If one or more of the weights are zero, these will never be chosen, which becomes evident when I introduce the selector later on.
The weights and their sum is then used as arguments for the int type RouletteSelector method. First it picks a random integer value between zero and the sum of the weights. Do note that the Random.Range method used for picking is exclusive on the maximum, that is the maximum value will never be picked.
After this the actual selection begins in a for-loop. This will go through the weights array, if the current weight is greater than the random weight, the loop will be ended with the break-statement and the current index value is returned as the output. For this reason the weights array and the objects array both should have the same amount of items, and of course in the same order as well.
On the other hand if the random weight is still greater than the current weight, the current weight will be subtracted from the random weight. This will be continued as long as the random weight is less than the current weight, since the random weight can be zero this condition will omit every weight that is also zero valued.
As an example, here is the coroutine for spawning the power ups to show how the roulette selector is used for spawning.