And you get a powerup! And you get a powerup!…
Adding a collectible object to our space shooter
Yesterday we covered adding the functionality of our triple shot powerup once it’s been collected. Collecting the powerup requires us to have a powerup object to collide with, triggering the activation of the power up. For this, we’ll drag the first sprite from our list of sprites provided for the animation of the Triple Shot Powerup collectible into our hierarchy, reset its transform, rename it, and reduce its scale to about 0.5. We’ll also attach a RigidBody2D with gravity set to 0 and a collider with Is Trigger checked so that we can work with the pass-through collision. This may seem like a lot of steps to run over quickly but these are basically the same steps we performed to get our enemy and laser ready for interacting with our player and each other, so they should be getting to be old hat now.
We’ll need a new C# script to hold the functionality of our power up, in this case we’ve called it Powerup as we’ll likely be reusing this script for other powerups in the future. Once we’ve added it to our Triple_Shot_Powerup object, we’ll add the movement code to our update function in the new script to move our powerup down the screen at a constant rate, add the code to destroy the gameobject when it goes off screen and add the code to handle collisions with our player, via the player tag. With this basic functionality in place (we’ve coded similar functionality in the Enemy and Laser objects), we’ll prefab the object so that we can instantiate it from our spawn manager.
In our Player class we need to create a public method that the Powerup script can call to activate our _tripleShotActive boolean from yesterdays article. We’ll also create a Coroutine and have it wait for 5 seconds and then turn the _tripleShotActive flag back to false, turning off the power up.
We’re going to use a special type of class called an enum to track which type of powerup is being activated. The values of an enum evaluate to numbers, usually starting at 0 and incrementing by one for each value. This gives us a nice way to make our code more readable. This will help when we add more powerups in the future.
Lastly we’ll call the new method on the player class from our collision logic on the powerup.
Next Time!
And now we have a collectible powerup object!
Tomorrow we’ll animate it to make it flash! If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.