More Power to the Shields!!

Making the power up a more powerful power up

Daniel Jennings
3 min readAug 8, 2021

Task:

When the Player collects a shield power up, we will allow 3 hits on the shield before it is disabled.

Plan:

We will need to add a life counter to our shield. This counter will start at 3 on collection of the shield. The shield currently expires with time. We should investigate whether to leave the timer. Collision on the shield is already implemented. We will need to expand on the collision logic to subtract a life per hit before disabling on the third hit.

In addition to lives we need to see somehow that the shield has changed. My initial thought on this was changing the color of the shield. It looks like we can access the color and albedo (transparency) via the sprite renderer.

Process:

Let’s start with adding shield lives.

Since the shield lives under the Player as well as the logic let’s add shield lives to the Player script.

Sweet!! That was easy!!

Now, when should we set this value?? We already have logic to collect the powerup. Let’s update the shield logic to make it work with our new scenario.

We still want the shield enabled. Then set the lives to 3 and set the shield color.

SetShieldColor gets the Sprite renderer and sets the color of the shield based on the number of shield lives remaining.

Speaking of lives remaining, how do we damage the shield??

If we detect a collision, and we have a shield, SetShieldDamage and return.

On shield running out of lives turn off the shield, else change the color.

Plan B — Adding a Shield class to hold the shield specific logic

After looking at the next challenge, and going back to the Player object to add more variables, it dawned on me that Player is getting pretty bloated. How can we help alleviate the bloat??

Creating a Shield class

There, I said it. Let’s move what we can from Player to a new Shield class.

We will have one variable for lives and a Property for IsShieldEnabled. The beautiful part of the property is that we can add our init logic in the setter area.

Back in our Player object we need to get the Shield component off of the gameObject. We set this once because GetComponent is an expensive call.

Out interaction with the Shield instance is very simple afterwards. Starting with our set true on collect.

And then our check of the property and calling the damage method.

And the cherry on top when object are inserted…

Everything works exactly as before!!

--

--