Preventing Player Damage

by Lance Gold

Adding GameObject behaviour to reduce damage prolongs the player’s game time

Return to index
Player object with Lives = 3

Player object with Lives = 3

Extend the Player object’s remaining lives. If the Player has three lives, then skip the next damage adjustment.

Collision with a Shield boost object

Collision with a Shield boost object

“_areShieldsActive” determines if damage is delayed.


    private bool _areShieldsActive = false;

    public void Damage()
    {
        if( _areShieldsActive )
        {
            _areShieldsActive = false;
            return;
        }

        _lives -= 1;

        if (_lives < 1)
        {
            // find SpawnManager game component, then cleanup destruction
            _spawnManager.OnPlayerDeath();
            Destroy(this.gameObject);
        }
    }

To prolong player lives, a routine is added to set _areShieldsActive to ‘true’.


public class Player : MonoBehaviour
{
...
    public void ShieldsActive()
    {
        _areShieldsActive = true;
    }
}

Next is to choose to call the ShieldsActive method of the Player class.

The OnTriggerEnter2D() with gameObjects occurs in the PowerUp class.


public class PowerUp : MonoBehaviour
{
,,,
    private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.tag == "Player")
        {
            // communicate with the player script, through other
            Player player = other.transform.GetComponent();
            if (player != null)
            {
                switch (_powerupID)
                {
...
                    case 2:
                        player.ShieldsActive();
                        break;
...
}