Adding a Health Collectable
This tutorial will cover adding a health collectable. This will be very similar to how you added powerups to the game. Examples of that can be found here and here. The health collectable will do two important things, first it will restore a life to the lives counter, and second it will repair one instance of visible damage on the player.
The First step is to create the object. Use the same sprite that you use for the players ship but make it half the size of the player object in each direction. In the example the player object is already half the size of the sprite so the health collectable is a quarter the size of the sprite. Add the Box Collider 2D and check Is Trigger. Add the Rigidbody 2D and set the Gravity Scale to 0. It should look like this.
Next, add the Powerup script to the health object. Set the Powerup ID to 4 and add in the power up sound for the audio clip.
The last two things to do in the Unity editor are to add the health collectable to the powerup prefab folder. Then, in the Spawn Manager increase the size of the Powerups array to 5 and add the health collectable in the last position as Element 4.
Next, you need to update the scripts. Start with the Spawn manager script. The only change you need to make here is in the SpawnPowerupRoutine function to update the range for the randomPowerUp. Now it will include 0 through 4.
int randomPowerUp = Random.Range(0, 5);
Next, go to the Player script. Add a function called CollectHealth. This function will do the opposite of what you do when the player takes damage. First check that the player doesn’t already have full health. Then increase the lives and update the UI. Then, check what the new lives is and repair the damage to the appropriate level by setting the engine damage animation to false.
public void CollectHealth()
{
if (_lives < 3)
{
_lives++;
_uiManager.UpdateLives(_lives); if (_lives == 3)
{
_rightEngine.SetActive(false);
}
else if (_lives == 2)
{
_leftEngine.SetActive(false);
}
}
}
The last step is in the Powerup script. In the switch statement in the OnTriggerEnter2D function add a new case for 4 which is the health collectable. In it call the CollectHealth function you just created.
case 4:
player.CollectHealth();
break;
That’s it! Now the player can replenish their lives and repair their ship..
Good Luck Adventurer!
-Chris