Space Shooter: Switch Statements and Speed Boost

Gerald Clark
3 min readJun 15, 2022

In this article I’m going to implement a new powerup. When collected the player’s speed will increase for 5 seconds and then return to normal.

First I created a Speed Boost Power Up prefab. Added a box collider 2D, a rigidbody 2D, and the Powerup script. There is a problem though. Since no logic exists to handle changing the player’s speed right now, when the speed boost is collected I still get tripleshot behavior. This is because I have hard-coded the triple shot behavior into the Powerup script. Instead of having the method player.TripleShotActive() called when I collide with the power ups, why not create a switch statement?

To do this you need an int variable that will hold a reference to specific GameObjects. In this case I made an int called powerUpIDs. In the collision logic for the Powerup I erased my previous code and added this switch statement.

When the player collides with a power up, this will look at the powerUpID of that object and call the case # associated with that ID #. In the inspector of the triple shot, I made the power up ID 0. In the speed power up I made the power up ID 1.

We’ve gone over the logic for when the player collides with the triple shot power up. I want to go over the speed implementation as well.

I’m handling this the same way I handled the triple shot logic. I’m changing the speed by a new variable called _speedmultiplier that I have set in the inspector. So the _speed increases by the _speedMultiplier value for 5 seconds and then goes back to normal.

Now for the spawn manager. Right now I’m still only spawning the triple shot.

instead of hardcoding the tripleshot in the spawn manager I created a new variable.

This is a GameObject array called powerups. Instead of instantiating the triple shot prefab I will instantiate a random powerup by creating a randomPowerUp variable. Setting it to a Random.Range(0,2); (Ill get into why 2 in a minute.)

Then when I instantiate the power up I’ll say Instantiate(powerups[randomPowerUp], etc etc);

The reason I want to say 0,2 instead of 1,2 is because Arrays start at 0. The first item(the triple shot) is index 0. The next (speed power up) is 1. I want to leave 2 there because I’ll be making a shield powerup next! See ya there!

--

--

Gerald Clark

Father Game Developer Music Composer Sound Designer