Shield Enemy in Unity
2D Space Shooter — Phase II: Core Programming Challenges
Objective: Create an Enemy with a shield or barrier to absorb hits without taking damage. The shield’s integrity will diminish and break after a set number of hits.
Note: You can learn about setting up the 2D Sprite Shield in the following aritcle- Creating a 2D Forcefield with Dynamic Color Changes . You can also learn how to change the color of the shield as it loses its integrity.
Programming the Behavior
- Add global variables for the following:
- Sprite Renderer: Enables us to tweak the Shield Sprite on and off.
- Shield Strength: The number of hits the shield can take before it becomes inactive. This variable isn’t absolutely necessary for one-hit shields unless you wish to have a way to edit the shield’s durability or make a shield that absorbs multiple hits.
-Optional-
- Shield Visualizer: To change the color of the shield as it loses integrity. This is optional and in my code, the shield only takes 1 hit before becoming inactive, however, I can see this logic here.
2. The SerializeField variables are to ensure that we can set them in the Inspector. Simply drag and drop the Shield Object(Shield Sprite) into the newly created spaces in the Inspector. Do this for both SerializeFields.
3. The following code needs to place where you detect damage being done to the Enemy. In my case, the damage is detected through collision logic, as such I subtract from the Shield Strength whenever a collision from the Player’s laser is detected. Since I set the Shield Strength to 1, it will only take 1 hit before becoming inactive, for this reason, I also set the Visualizer to false. Setting the visualizer to false will make the Sprite disappear.
4. It is absolutely important that the Enemy does not take damage before the shield loses all its strength. This can be controlled by setting a condition before you destroy the Enemy Object. As long as the Shield Strength is greater than 0, a return statement will execute. This means that the code outside the if-statement will not execute therefore the Enemy Object won’t be destroyed until it stops being true.
Alternatively, for one-hit shields, you can use a boolean instead to keep track of the shield being active — as long as it is true, the return statement will execute.
The Result:
This article is part of a series of Core Programming Challenges from GameDevHQ. In the following article, I will be talking about how to randomize the enemies so that some of them spawn with shields while others don’t.