Repairing the Player with a Powerup
In Galaxy Shooter, when the player takes damage, that damage stays forever. It feels pretty bad to be stuck with permanent damage from a single mistake! Today, we will add a powerup capable of fixing that.
Just like the last time we added a powerup, we can make some minor adjustments in the Powerup script. Just create a new powerup type and a new case in the GrantPowerup switch statement.
However, we are going to have to change a lot of things in the Player script, since right now we don’t have a way for it to repair damage. For reference, here is the OnTakeDamage method used by enemies and their lasers.
We will want to have some of this functionality in a helper method that can handle both losing and gaining lives. We also want a way to turn the damage effects on or off, depending on whether we take damage or repair it.
Lets start by changing some variables. _lives should no longer be serialized, and we want _maxLives as a new serialized variable so we can change it in the inspector.
Below is a new helper function that controls the damage effects, which are fire trails that appear when the player is damaged. (We set that up a while ago.) The best practice is to code something that will work no matter what the player’s maximum life is, and how many damage effects there are. If the player has 1 life remaining, we we would want to turn on all the damage effects at once.
This loop accomplishes that by turning on more effects the lower the player’s life is. It will also turn off effects if the player’s life increases.
By creating this helper method, now controlling the player’s life total is a lot simpler. We can add the amount of lives gained to the _lives variable, and make sure it stays between 0 and max. We tell the UI Manager to update its life counter image, and also call PlayerDeath if lives are zero.
By having ToggleDamageEffects as its own helper function, it makes this GainLives much simpler and easier to manager in the future.
Now the public methods are really simple. When something tells the player to take damage, it gains a negative life (thus losing a life). If a powerup tells the player to repair, it gains a life. Everything is handled by the helper functions we created, even in cases where the life gain or less is greater than one.
Now all that’s left is to create the Repair_Powerup prefab (complete with the new Repair type), and add it to the Spawn Manager.
Now we finally have a way for the player to repair itself and get rid of that nasty looking hull damage. In the future, we’ll even be able to handle more max life and stronger damage and repair effects.