Shields up! Giving your AI random shields.
So today I’m going to be giving our enemy AI some shields. I’ve chosen to just give it randomly — 25% chance that when instantiated the enemy will come with a shield. It’s just a 1 shot shield but when there are a lot of enemies on screen it really increases the challenge.
First I just grabbed the player shield sprite and changed the color of it to give the enemy a different look.
Note that I made the new enemy_shield a child of the enemy. When you do that it will follow the enemy where ever it goes. Easy trick.
Now you just uncheck the box at the top and make it inactive. You will turn this on using code whenever our random ship gains access to the shield.
Inside of our enemy script we are going to add this code.
To start we need to create a bool variable that we can turn the shield object on and off (that’s the little check mark box you turned off in Unity. Then we create an int variable that will hold the hits the shield can take. We can increase this to more in later waves if we like. Then we need to assign the shield sprite to the game object we created in Unity, we SerializeField it so we can just drag the sprite into the empty box in Unity. Lastly an int variable that will store the random number we will produce to see if the newly created enemy will indeed come with a shield.
Now I just created 2 functions. The first will be checking to see if the enemy is given a shield when it spawns. I just assign a random number to _randomShieldNumber (in this case I just gave it a 50% chance for testing, I will lessen this to 1–4). Then the code will check if the number is 1 and if so it will call the next function I created — ShieldActive.
In the ShieldActive() function I assign 1 hit to the shield, set the shield object to active and then turn on the sprite to show the shield.
Now I did have a little trouble with this at the start. When the collision was taking place it would destroy the shield ok, but then the enemy would become invincible. The problem was that it was setting the _isShieldActive immediately after this so it was giving the enemy a “shield” with no sprite and making it indestructible. A quick little Coroutine delaying that setting action by .5f stopped that.
I’ll just show you one interaction if there is a collision for space savings, but there is code for the laser and player interaction as well. Basically in the above, if the missile collides AND the isShieldActive is true, it is going to destroy the missile, subtract 1 from the shildPower, set the sprite to false (shield will disappear) and then run the ChangeShieldActiveDelay coroutine.
This works pretty cool in fact, have a look!
So that’s it, pretty good. I’ll set that back to 25% now so they don’t kill the player too fast.
Tomorrow I’m going to give the players even more problems by making aggressive “Ram” ships. These will come down as usual but when they detect the player in a proximity range they will charge towards it to ram it!