Gaming in Unity

12. Unity 2D Game 8 - Damage Zone

(../img/unity-12-2d-game-8-damage-zone/2d-game-8-damage-zone-header.png)

A Damage Zone will reduce the health of SpriteCharacter!

Step 1 - Adding Damage Zone

First, import DamageZone.png into Assets -> Environment.

Add DamageZone to the Hierarchy.

Add a Box Collider 2D to the DamageZone GameObject and enable Is Trigger.

(../img/unity-12-2d-game-8-damage-zone/2d-game-damage-zone-step-1.jpg)

We now need to write a script to make the area reduce health.

Create a new script called DamageZone in Assets -> Scripts.

This will look more or less the same as the HealthCollectible script with three key differences:

This line will ensure the zone continuously applies the damage over time:

void onTriggerEnter2D will be changed to onTriggerStay2D.

This will make health be reduced and not increased by the zone:

controller.changeHealth(1) will now be controller.changeHealth(-1).

Also remove Destroy(gameObject) so the damage zone doesn't disappear after collision.

(../img/unity-12-2d-game-8-damage-zone/2d-game-damage-zone-step-1-2.jpg)

Attach the DamageZone script to the DamageZone object in the Hierarchy.

Press play and move SpriteCharacter into the DamageZone and notice health almost immediately decrease to 0. SpriteCharacter also won't take damage if standing still.

To fix damage while standing still, select SpriteCharacter and change Sleeping Mode to Never Sleep in the Rigidbody 2D component.

(../img/unity-12-2d-game-8-damage-zone/2d-game-damage-zone-step-1-3.jpg)

Step 2 - Adding Invincibility to SpriteController

Now, to stop health immediately decreasing to 0, we need to add to SpriteController script.

Open SpriteController script.

Add three new variables:

public float timeInvincible = 2.0f;
bool isInvincible;
float invincibleTimer;

(../img/unity-12-2d-game-8-damage-zone/2d-game-damage-zone-step-2.jpg)

Add an if statement to void Update(). This counts down the time that SpriteCharacter remains invincible.

(../img/unity-12-2d-game-8-damage-zone/2d-game-damage-zone-step-2-2.jpg)

Add a few lines of code to ChangeHealth to check whether SpriteCharacter is invincible.

(../img/unity-12-2d-game-8-damage-zone/2d-game-damage-zone-step-2-3.jpg)

SpriteCharacter should now only get damaged every two seconds of staying in the damage area!

Created by: David Corish