2D Galaxy Shooter P1: Adding a Health Power-up!

My first challenge for the phase 1 framework is to add a health collectible!

Since there isn’t a sprite for the Health power-up, I did a little bit of photoshopping an existing power-up sprite.

I grabbed the speed collectible sprite and altered the colors, and changed the text. It looks like it came with the asset package!

I turned this into a prefab with its necessary components in Unity.

Since we have a modular power-up system, it’s easy to add as many as we wish easily. I opened up the Powerup script to add the following to our enum:

public enum PowerupType 
{
None,
TripleShot,
Speed,
Shield,
Health
}

I went ahead to also modify our switch inside of OnTriggerEnter2D().

private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag(“Player”))
{
var player = other.transform.GetComponent<Player>();
if(player != null)
{
switch (_powerupType)
{
case PowerupType.TripleShot:
player.TripleShotActive();
break;
case PowerupType.Speed:
player.SpeedBoostActive();
break;
case PowerupType.Shield:
player.ShieldActive();
break;
case PowerupType.Health:
player.HealthActive();
break;

default:
_powerupType = PowerupType.None;
break;
}
}
_audioManager.PlayPowerupSound(); Destroy(gameObject);
}
}

In bold, I implemented the logic to have the power-up of type Health collide with the player.

In the health collectible prefab, I went ahead to change the power-up type to Health.

The next part was tricky for me. I tried many ways to add the extra life but _lives wouldn’t update when playtesting in play mode.

So I decided to rely on properties. I added logic to the property of _lives so that when the player reaches 3 or greater, to remain 3. I did the same if _lives equal to 0 or less, to remain 0. This also means Game Over, man!

public int Lives
{
get { return _lives; }
set
{
_lives = value;
if (_lives >= 3)
_lives = 3;
if (_lives <= 0)
_lives = 0;

}
}

The logic of the value remaining 0 is not needed here, but I decided to keep it.

And of course, here’s the function that is called from the Powerup script:

public void HealthActive()
{
Lives += 1;
}

This will give a life to the player when a collision is detected with the health collectible instance. The Lives property has logic now so this all works great!

Last but not least, I need to reference the Health power-up prefab to the spawn manager.

Well, there you go! First challenge complete! I am pumped! For tomorrow’s challenge, I will implement an ammo counter.

Thank you for your time!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gabriel Perez

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.