SPACE SHOOTER

LIVES AND RESPAWNING

LIVES

MAIN

Lives Counter

First we'll need to add a global variable to the top of our program called lives. Start it at five.

int lives = 5;


Next, we'll want to display this in our program. Add code to your render() method to display it:

textSize(24);

fill(255);

text("Lives: " + lives, 50, 100);

Test your program - it should be displaying "Lives - 5" at the top.

RESPAWNING

PLAYER

Respawning the Player
We're going to override the die() method for the player class. This allows us to only remove the player from the game when it is out of lives. When the player still has lives, we'll simply move it, restore health, and reduce the life counter.


void die()

{

if(lives > 0)

{

x = width / 2;

y = height - 200;

curHealth = maxHealth;

lives--;

}

else

{

curHealth = 0;

isAlive = false;

}

}

Test your program! The player should be able to respawn.

INVULNERABILITY

PLAYER

Why invulnerability on respawn?

This is an optional step. All projects benefit from it, but it's only *required* if your player does not have a health system implemented.

A common problem in this kind of game is that the player might respawn on top of a bullet or in a dangerous location. To make things more easier for our players, we'll make their ship invulnerable for a few seconds.


The Timer

We'll follow create an invulnerability timer with a simple rule:

  • If invulnerability timer is zero, it means the player can take damage

  • Otherwise, the player is invulnerable

At the top of the player class, we'll create an invulnerability timer.

int invulnTimer = 0;


In the die() method, we'll need to add a line to set invulnerability to some value each time the player respawns.

invulnTimer = 120;


In the act() method, we'll decrease that time by one so long as it is greater than zero.

if(invulnTimer > 0)

{

invulnTimer--;

}

Displaying Invulnerability

A common strategy for showing invulnerability is to cause the image to "flicker" - displaying every other frame.

In your player's render method, we'll modify your call to the super.render() by surrounding it with a conditional. We want to render the image in one of two scenarios:

  • The timer is zero (player can take damage)

  • The timer is even (invulnerable - show every other frame)


void render()

{

if(invulnTimer == 0 || invulnTimer % 2 == 0)

{

super.render();

}

// ... other code ...

}

Test your program - the player won't actually be invulnerable, but it should flicker for about two seconds on respawn.

Actually Blocking Damage

Ignoring damage is actually pretty simple: we'll override the takeDamage method. Rather than rewriting it, we'll just say: "If I am not invulnerable, take damage like normal."


void takeDamage(float amount)

{

if(invulnTimer == 0)

{

super.takeDamage(amount);

}

}


Test your program - invulnerability should be working!