Triple Shot!
Determining How Long Powerup Effects Should Last
We have some simple powerup functionality, in that our animated object spawns randomly and moves down the screen. Our first powerup is called Triple Shot, which coincidentally, will allow us to fire three shots at once. But when we collect the powerup, we don’t want to have triple shot forever. We need to create another cooldown method. Before we can run this cooldown method though, we need to actually create the triple shot.
To do so, we can create a new gameobject, make it a prefab and have it contain three of our laser prefab objects. Position them appropriately with your player. Since we are using our laser prefabs, the movement and collision with enemy functionalities are already in place.
Now we can create a bool within our player script to check if our triple shot is active, create a GameObject variable to store our new prefab, then change our FireLaser method.
Now we need to change our bool. We can do this with script communication when the powerup collides with our player.
For our powerup to have this functionality we need to assign it some physics. Add a suitable 2D Collider and set it to Is Trigger. We also need a 2D Rigidbody (Remember to set the Gravity Scale to 0).
Within our powerup script we can use OnTriggerEnter2D to check if the other.tag is equal to the “Player”. Now we can get the Player component and access public methods. Remember to null check.
Our public method within our player script is going to look like the following:
This sets our bool to true, allowing us to Instantiate the triple shot prefab. Then we start a Coroutine to function as our cooldown system.
Before we look at the Coroutine, lets go back to our powerup script and call this method when we collide with the player.
Back to our player script, our Coroutine can call the following.
We can specify an amount of seconds to wait, before then switching our bool back to false, setting our player back to firing one laser. But determining how long powerups should last can take time and various playtests. With more elements added later, we may want to alter this. So instead we can create a private float that we Serialize so we can change it in the inspector.