Journal 18 — How Long Should Powerups Last? Unity Practice
In this example, we have added a powerup for triple shot, but now we need to add programming for four actions:
— Spawn the powerups at some interval, random or predefined
— Move the powerups and destroy them when off screen
— Collide with the Player and activate the powerup
— Turn off the powerup after a certain duration
In working through this exercise, we need to use script communication to handle all these actions.
— SpawnManager script will handle instantiation of powerups, and will stop spawning if the Player script notifies the Player has died.
— Powerup script can handle movement, destroying itself, and the collision event. The Powerup script communicates with the Player script to notify the triple shot should now be active.
— Player script handles switching the laser weapon from one laser to a triple shot laser if it’s active, and also handles the duration.
As described above, in the SpawnManager, we will have a new coroutine and IEnumerator for spawning the power ups.
Use the same approach as previously done for spawning the enemies, but in this case it is for spawning the powerups. There is a local variable used to randomly spawn additional powerups between 5 and 9 seconds.
Over in the Powerup script, when instantiated the powerups move down the screen, and are destroyed if they go off the screen.
The powerup includes an OnTriggerEnter2D check for collisions with the Player, and activates a function in the Player script.
In the Player script, the triple shot is set to active which changes the laser weapon.
How long to set the triple shot to last is up to you. I have initially set it at the same time as another powerup should spawn, or worst case about half the time until a new powerup spawns. The powerup duration could be shortened on harder levels and you could make it take longer for powerups to spawn. Another options is to make the player collect a few powerups as “fragments” in order to finally activate one.
Thank you for stopping by!