2D Galaxy Shooter P2: Balanced Spawning!

Gabriel Perez
2 min readMay 5, 2021

For today's challenge, I implemented a simple probability system for a balanced spawn system.

There were quite a few ideas I had to make it modular but it did not work as intended. So I went with a simple hard-coded approach. If anyone has a better idea to improve this system, please feel free to let me know in the comments below!

In the SpawnManager script, I created a new function called “PowerupProbabilityCheck().” It takes in a Vector for a random ‘X’ position where it will spawn.

private void PowerupProbabilityCheck(Vector3 randomXposition)
{
var randomValue = Random.value;
if (randomValue > 0f && randomValue <= .05f) //Gods Wish
Instantiate(_powerupPrefabs[0], randonXposition, Quaternion.identity);

else if (randomValue > 0.05f && randomValue <= 0.2f) //Shields
Instantiate(_powerupPrefabs[1], randonXposition, Quaternion.identity);
else if (randomValue > 0.2f && randomValue <= 0.4f) //Health
Instantiate(_powerupPrefabs[2], randonXposition, Quaternion.identity);
else if (randomValue > 0.04f && randomValue <= 0.6f) //TripleShot
Instantiate(_powerupPrefabs[3], randonXposition, Quaternion.identity);
else if (randomValue > 0.6f && randomValue <= 1f) //Ammo
Instantiate(_powerupPrefabs[4], randonXposition, Quaternion.identity);
}

We want to check a random value against the desired percentage for when to spawn a certain type of power-up.

In bold, I check if the randomValue is greater than zero and if it's less or equal to 0.05 percent. If it is, then we want to instantiate the God’s Wish power-up.

The same goes for the rest of the conditions!

I called the function in the power-up routine:

private IEnumerator SpawnPowerUpRoutine()
{
if (_gameManager.IsNewScene)
{
yield return new WaitForSeconds(_waitToSpawn);
}
while (!_stopSpawning)
{
float randomX = Random.Range(-11, 11);
Vector3 randomXposition = new Vector3(randomX, 8, 0);
PowerupProbabilityCheck(randomXposition); float randomTime = Random.Range(6, 20);
yield return new WaitForSeconds(randomTime);
}
}

The function call takes an argument of a Vector. So I passed in randomXposition as the argument.

I did the same thing for the enemies! Like I have stated earlier, this approach is not modular, but it does the job!

That is all for today! Thank you for your time.

--

--

Gabriel Perez

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.