outOfBoundsKill equivalent in Phaser 3

Viewed 2473

I have used Phaser 2 for a while but recently converted to Phaser 3 and I want to know if there is a method or member that might be equivalent to 'outOfBoundsKill'. I have an Arc Object in Phaser 3 and applied gravity to it and I want to make sure it is killed or destroyed when it is out of bounds of the canvas.

More about outOfBoundsKill: https://phaser.io/docs/2.6.2/Phaser.Sprite.html#outOfBoundsKill

I have tried this code sample and it did not destroy the arc object, 'ball' is the arc object.

ball.on('worldbounds', function() {
  if (!Over) {
    ball.destroy();

    HealthBar.livesLeft -= 1;
    HealthBar.cs.scale.x = HealthBar.livesLeft / HealthBar.lives;

    var shake = this.sound.add('shake');
    shake.play();
  }
}, this);

1 Answers

There is no built in equivalent, that I could find, but I do know how to replicate it

const sprite = this.physics.add.sprite(x, y, 'key');

// Turn on wall collision checking for your sprite
sprite.setCollideWorldBounds(true);

// Turning this on will allow you to listen to the 'worldbounds' event
sprite.body.onWorldBounds = true;

// 'worldbounds' event listener
sprite.body.world.on('worldbounds', function(body) {
  // Check if the body's game object is the sprite you are listening for
  if (body.gameObject === this) {
    // Stop physics and render updates for this object
    this.setActive(false);
    this.setVisible(false);
  }
}, sprite);

Do not use destroy(). It is computationally expensive and requires that you recreate the object again (if there isn't anything pointing to it already).

Related