How to set collider with world bounds (Phaser)?

Viewed 1266

I'm using Phaser.io

I just learned how to set a collider function:

this.physics.add.collider(enemies, platforms, function (enemy) {
  enemy.destroy();
  gameState.score += 10;
});

But I would like to do the same thing without the platform. Instead of the platform, I would like to use the world bounds.

I know you can set world bounds like this:

player.setCollideWorldBounds(true);

I've tried:

this.physics.add.collider(enemies, this.worldBounds, function (enemy) {
  enemy.destroy();
  gameState.score += 10;
});

But this doesn't work.

Any ideas?

1 Answers

I have found a solution for you:

First, set your enemy's sprite to collide with the setCollideWorldBounds(true) like so:

enemy.setCollideWorldBounds(true);

Second, turn the option for your enemy's sprite to listen for WorldBound events like so:

enemy.body.onWorldBounds = true;

Third & lastly, set the "wordbounds" event listener & make the enemy disappear like so:

enemy.body.world.on('worldbounds', function(body) {
  // Checks if it's the sprite that you'listening for
  if (body.gameObject === this) {
    // Make the enemy sprite unactived & make it disappear
    this.setActive(false);
    this.setVisible(false);
  }
}, enemy);
Related