Giving Enemies Shields!

The last few challenges were quite a workout! Thankfully this one seems to be straightforward: Give some enemies the ability to have a shield that can be hit once.

Great! It sounds like I can code that directly into the shield and just give it to the enemy. First, let’s make a shield:

Well, that looks kind of boring. Let’s make that its idle state and then go to an animation when its hit.

Much better! You can disregard the last few frames since they’re repeats. They’re artifacts of an awesome program called BitmapFlow that will make in-betweens of your sprites. I highly recommend it!

After importing and slicing the sprites, we’ll create a prefab out of it, attach a rigidbody2d and capsulecollider2d and make it a trigger. Next we’ll add a script to it:

Extremely straightforward, grab the animator component, and in the OnTriggerEnter2D, if it’s an enemy or enemy laser, ignore it. If it’s the player, damage the player, and if it’s a laser, Destroy the laser and destroy itself.

When Destroying itself, the shield will trigger the “isShot” parameter to let the animator know to play the shield disappating, but we’ll also play it just to be sure. we wait a fraction of a second to let the animation play and then we destroy the object and the enemy no longer has a shield to protect it! Easy enough! Now let’s give it to random enemies in the spawner.

The ChooseEnemy() function was what we went over yesterday with weighted probabilities. We then instantiate it into the scene, and then we use a random value to decide whether that enemy gets shields or not. If it does hit that 30 percent chance, it will access the enemy script and activate the SpawnShield routine.

In the Enemy script, we have a variable called _enemyShieldHolder that we dragged the shield into in Unitys inspector panel. We instantiate that prefab into a variable called _enemyShield and parent that object to the enemy so it will follow along in its movement. If we didn’t do this step, we’de instantiate it, but the ship would move down and the shield would stay back. Attaching it to the enemy parent makes it move along with it.

Let’s see it in action!

Looks great! Next we’ll work on an aggressive enemy that tries to ram you!

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