Day 3: Spawning Enemies and Adding Collision Detection
Welcome to Day 3 of our series on building a cross-platform mobile game with React Native and Phaser. Today, you’ll learn how to spawn multiple enemies, detect collisions between game objects, and handle in-game events when objects interact.
๐ง What Youโll Learn
- How to create multiple enemy objects
- How to use Phaserโs Arcade Physics engine
- How to detect and respond to overlaps/collisions
- How to structure your code for repeated game object generation
๐ง Step 1: Update Phaser Config for Physics
In your assets/phaser/game.html
, modify the Phaser config object:
const config = {
type: Phaser.AUTO,
width: 320,
height: 480,
physics: {
default: 'arcade',
arcade: {
debug: false
}
},
scene: {
preload,
create,
update,
}
};
๐ผ๏ธ Step 2: Update Assets and Preload
Inside your preload()
function:
function preload() {
this.load.image('logo', 'https://labs.phaser.io/assets/sprites/phaser3-logo.png');
this.load.image('enemy', 'https://labs.phaser.io/assets/sprites/ufo.png');
}
๐พ Step 3: Create Player & Enemies
Update your create()
function to spawn a player and enemy group:
let player;
let enemies;
let score = 0;
function create() {
// Player
player = this.physics.add.image(160, 400, 'logo');
player.setCollideWorldBounds(true);
// Enemy group
enemies = this.physics.add.group();
// Spawn enemies every second
this.time.addEvent({
delay: 1000,
callback: () => {
const x = Phaser.Math.Between(20, 300);
const enemy = enemies.create(x, 0, 'enemy');
enemy.setVelocityY(100);
},
loop: true
});
// Input to move player
this.input.on('pointermove', function (pointer) {
player.x = pointer.x;
});
// Collision detection
this.physics.add.overlap(player, enemies, hitEnemy, null, this);
}
๐ฅ Step 4: Handle Collisions
Add a hitEnemy()
function:
function hitEnemy(player, enemy) {
enemy.destroy();
score += 1;
console.log('Hit! Score:', score);
}
๐ Step 5: Update Game Loop
Inside update()
:
function update() {
// You could add logic here for win/lose conditions later
}
๐ฑ Test It on Device
- Save
game.html
. - Launch
expo start
. - Open in Expo Go or emulator.
- Watch enemies fall. Move the player with your finger.
- When the player touches an enemy โ ๐ฅ the enemy disappears and score increases in console.
โ What Youโve Achieved
- Spawned enemies using timed events
- Used Arcade Physics to enable motion and collision
- Handled collision between player and enemies
- Implemented player controls via pointer movement
๐ Up Next
In Day 4, weโll add a score display, health system, and game over screen. This will make your game feel real and track player progress visually.
You’re building a real mobile game โ and it’s starting to get fun!