In this section, you’ll learn how to detect and handle collisions and overlaps between game objects in Phaser. Understanding these concepts is essential for creating interactive and dynamic games, such as platformers, shooters, or puzzle games.


  1. Key Concepts

Let’s clarify the main ideas:

  • Collision: When two objects physically interact and cannot pass through each other (e.g., a player hitting a wall).
  • Overlap: When two objects occupy the same space, but do not physically block each other (e.g., collecting a coin).
  • Physics Engine: Phaser uses built-in physics systems (like Arcade Physics) to manage collisions and overlaps.
Concept Blocks Movement? Triggers Event? Example
Collision Yes Yes Player hits a wall
Overlap No Yes Player collects a coin

  1. Enabling Collisions and Overlaps

2.1. Setting Up Physics

Before detecting collisions or overlaps, ensure your game objects have physics enabled.

// Enable physics on a sprite
this.physics.add.existing(player);
this.physics.add.existing(wall);

Or, when creating sprites:

const player = this.physics.add.sprite(100, 100, 'player');
const wall = this.physics.add.staticSprite(200, 100, 'wall');
  • this.physics.add.sprite: Creates a dynamic (movable) sprite.
  • this.physics.add.staticSprite: Creates a static (immovable) sprite.

2.2. Detecting Collisions

Use this.physics.add.collider to make two objects collide:

this.physics.add.collider(player, wall);
  • This prevents the player from passing through the wall.
  • You can also pass a callback function to handle what happens when a collision occurs.

With a callback:

this.physics.add.collider(player, wall, () => {
  console.log('Player hit the wall!');
});

2.3. Detecting Overlaps

Use this.physics.add.overlap to detect when two objects overlap:

this.physics.add.overlap(player, coin, collectCoin, null, this);

function collectCoin(player, coin) {
  coin.destroy(); // Remove the coin
  // Add score or play sound here
}
  • Overlap does not block movement.
  • The callback function is called whenever the player and coin overlap.

  1. Practical Example

Let’s create a simple example where a player collects coins and cannot pass through walls.

class MyGameScene extends Phaser.Scene {
  constructor() {
    super({ key: 'MyGameScene' });
  }

  preload() {
    this.load.image('player', 'assets/player.png');
    this.load.image('wall', 'assets/wall.png');
    this.load.image('coin', 'assets/coin.png');
  }

  create() {
    // Create player and wall
    this.player = this.physics.add.sprite(100, 100, 'player');
    this.wall = this.physics.add.staticSprite(200, 100, 'wall');
    this.coin = this.physics.add.sprite(150, 100, 'coin');

    // Enable collision between player and wall
    this.physics.add.collider(this.player, this.wall);

    // Enable overlap between player and coin
    this.physics.add.overlap(this.player, this.coin, this.collectCoin, null, this);

    // Enable arrow key input
    this.cursors = this.input.keyboard.createCursorKeys();
  }

  update() {
    // Simple movement
    this.player.setVelocity(0);
    if (this.cursors.left.isDown) {
      this.player.setVelocityX(-100);
    } else if (this.cursors.right.isDown) {
      this.player.setVelocityX(100);
    }
    if (this.cursors.up.isDown) {
      this.player.setVelocityY(-100);
    } else if (this.cursors.down.isDown) {
      this.player.setVelocityY(100);
    }
  }

  collectCoin(player, coin) {
    coin.destroy();
    console.log('Coin collected!');
  }
}

Explanation:

  • The player can move with arrow keys.
  • The player cannot pass through the wall (collision).
  • When the player touches the coin, the coin disappears (overlap).

  1. Exercise

Task:
Create a scene where a player collects three coins placed at different positions. When all coins are collected, display a message: "All coins collected!".

Starter Code

class CoinGame extends Phaser.Scene {
  constructor() {
    super({ key: 'CoinGame' });
  }

  preload() {
    this.load.image('player', 'assets/player.png');
    this.load.image('coin', 'assets/coin.png');
  }

  create() {
    this.player = this.physics.add.sprite(100, 100, 'player');
    this.coins = this.physics.add.group({
      key: 'coin',
      repeat: 2,
      setXY: { x: 200, y: 100, stepX: 100 }
    });

    this.physics.add.overlap(this.player, this.coins, this.collectCoin, null, this);

    this.cursors = this.input.keyboard.createCursorKeys();
    this.collected = 0;
  }

  update() {
    this.player.setVelocity(0);
    if (this.cursors.left.isDown) {
      this.player.setVelocityX(-100);
    } else if (this.cursors.right.isDown) {
      this.player.setVelocityX(100);
    }
    if (this.cursors.up.isDown) {
      this.player.setVelocityY(-100);
    } else if (this.cursors.down.isDown) {
      this.player.setVelocityY(100);
    }
  }

  collectCoin(player, coin) {
    // Complete this function
  }
}

Solution

collectCoin(player, coin) {
  coin.destroy();
  this.collected += 1;
  if (this.collected === 3) {
    this.add.text(100, 200, 'All coins collected!', { fontSize: '24px', fill: '#fff' });
  }
}

Common Mistakes & Tips:

  • Make sure to destroy the coin so it disappears.
  • Use a counter to track how many coins have been collected.
  • Remember to check the count after destroying the coin.

  1. Summary

  • Collisions block movement and can trigger events.
  • Overlaps do not block movement but can trigger events (like collecting items).
  • Use this.physics.add.collider for collisions and this.physics.add.overlap for overlaps.
  • Always enable physics on objects you want to check for collisions or overlaps.
  • Practice by creating interactive scenes with both collisions and overlaps.

Next: You’ll learn how to make objects interactive and respond to events in Interactive Objects and Events.

© Copyright 2024. All rights reserved