Day 4: Displaying Score, Health, and Creating a Game Over Screen
Welcome to Day 4 of building your cross-platform mobile game with React Native and Phaser. You’ve got enemies spawning and collisions working. Now it’s time to add a score counter, a health system, and a game over screen to make your game feel polished.
๐ง What Youโll Learn
- Displaying text (score/health) in Phaser
- Tracking player health on collision
- Creating a game over condition and restart logic
๐๏ธ Step 1: Add Global Variables
Update your variables:
let player;
let enemies;
let score = 0;
let health = 3;
let scoreText;
let healthText;
let gameOver = false;
๐งช Step 2: Display Score and Health in create()
Add the text overlays:
scoreText = this.add.text(10, 10, 'Score: 0', {
font: '16px Arial',
fill: '#ffffff'
});
healthText = this.add.text(200, 10, 'Health: 3', {
font: '16px Arial',
fill: '#ffffff'
});
๐ฅ Step 3: Update Collision Logic
Modify hitEnemy()
:
function hitEnemy(player, enemy) {
enemy.destroy();
health -= 1;
healthText.setText('Health: ' + health);
if (health <= 0) {
endGame.call(this);
}
}
๐ Step 4: Create the Game Over Screen
Add the endGame()
function:
function endGame() {
gameOver = true;
this.physics.pause();
enemies.clear(true, true);
this.add.text(60, 200, 'Game Over', {
font: '32px Arial',
fill: '#ff0000'
});
this.add.text(60, 260, 'Tap to Restart', {
font: '16px Arial',
fill: '#ffffff'
});
this.input.once('pointerdown', () => {
this.scene.restart();
score = 0;
health = 3;
gameOver = false;
});
}
๐ Optional: Update Score on Collision
If you want score for surviving or defeating enemies, you can increment score += 1;
in a different logic block, or keep it tied to destroyed enemies.
In hitEnemy()
:
score += 1;
scoreText.setText('Score: ' + score);
๐ฑ Step 5: Run and Test
expo start
- Move your finger to avoid enemies.
- Colliding with 3 enemies ends the game.
- Youโll see a โGame Overโ screen and be able to tap to restart.
โ What Youโve Achieved
- Added a dynamic score and health HUD
- Built a working game over screen
- Enabled tap-to-restart for replayability
- Made your mobile game feel real and interactive
๐ Up Next
In Day 5, weโll add levels, speed progression, and start introducing power-ups. This will keep the gameplay fresh and challenging.
Youโve got a real game loop now โ and soon, a full playable game!