Damaging the Enemy
Last updated
Last updated
This tutorial will implement dealing damage to an Enemy. Rather than immediately destroying the Enemy when it collides with a Bullet, we'll implement health points (HP) which can be reduced when an Enemy collides with a Bullet. Once an Enemy's HP is reduced to 0, it will be destroyed.
Typically enemies will have two values for HP:
MaxHP - the starting number of HP when an Enemy is first spawned
CurrentHP - the number of HP that the enemy currently has
The MaxHP is a designer variable - a variable which a game designer may change during the development of the game to adjust difficulty. We'll define this in Glue so it can be changed easily. By contrast, CurrentHP is a logic variable - a variable which is used in game logic and which should not be modified by a game designer. It will initially be assigned to MaxHP and will be reduced whenever the Player takes damage. To define a MaxHP variable:
Select the Enemy entity
Click on the Variables tab
Click the Add New Variable button
Select the int type
Enter the name MaxHP
Click OK
Set the new MaxHP variable to 6
Now we can add the CurrentHP value to the Enemy:
Open the project in Visual Studio
Open Enemy.cs
Add the CurrentHp variable and modify CustomInitialize as shown in the following code snippet
In a typical game, whenever an Enemy takes damage the game may perform many actions such as:
Flashing the Enemy or playing some visual effect
Playing a sound effect
Showing the amount of damage dealt (as a floating number)
Modifying how much health is shown in a health bar
Destroying the Enemy and showing a death effect if the Enemy has died
Keeping this logic in the Enemy.cs file can help keep code organized, so we'll be adding the following function to the Enemy.cs file:
Be sure to make the TakeDamage method public so it can be called from outside of the Enemy class.
Now we can create a collision relationship between the BulletList and EnemyList objects in the GameScreen:
Expand the GameScreen Objects folder
Drag+drop the BulletList object onto EnemyList\
Select the new BulletListVsEnemyList relationship
Click on the Collision tab
Click the Add Event button
Accept the defaults and click OK
Now we can fill in the event method. Open GameScreen.Event.cs and modify the BulletListVsEnemyListCollisionOccurred method as shown in the following snippet:
Now we can shoot at the enemy. After six shots, the enemy is destroyed.
Now we've created a game where we can destroy an enemy with 6 shots. A real game would have more than one enemy, but if we add additional enemies, our game will automatically collide bullets against each enemy, and each enemy will keep track of its own HP.