Jump to content

How to kill object from group?


ekeimaja
 Share

Recommended Posts

Everytime player collides to any enemy, that enemy object needs to be killed. Enemies are made as group. I need some simple solution for this.

this.enemies = this.game.add.group();

        for (var i = 0; i < 90; i++)
        {
            this.enemy = this.enemies.create(x,y, i);
            this.game.physics.p2.enable(this.enemy);
            this.enemy.body.setMaterial(this.enemyMaterial);
            this.enemy.body.static = true;
            this.enemy.body.collideWorldBounds = true;
            this.enemy.outOfBoundsKill = true;
            this.enemy.body.velocity.x = 290 + Math.random() * 87;
            this.enemy.body.setCollisionGroup(this.enemyCG);
            this.enemy.body.collides([this.playerCG, this.wallsCG]);
        }

this.player.body.collides(this.enemyCG, this.killEnemy, this);

none of these does not work. How it works in the example then?

killEnemy: function (player, enemy) {

//this.enemy.animations.play('die');

// this.enemy.kill();
// this.enemy.destroy();
// this.enemies.remove(this.enemy);
}

 

Link to comment
Share on other sites

Because 'this.enemy' can only refer to one enemy, and is being overridden 90 times. It only contains the last enemy since it was the 90th enemy that was the last one to be set to this property. The 'killEnemy' function called by the collision routine contains an 'enemy' parameter which can be used to reference the enemy the player collided with:

killEnemy: function (player, enemy) {
    // in here, 'player' is the player, and 'enemy' is the enemy the player collided with
    enemy.animations.play('die');
    enemy.kill();
    enemy.destroy();

    // this.enemies still refers to the group, so we can remove the enemy from the group
    this.enemies.remove(enemy);
}

 

Link to comment
Share on other sites

killEnemy: function (player, enemy) {
	enemy.animations.play('die');
	enemy.events.onAnimationComplete(function(enemy) {
		enemy.kill();
		enemy.destroy();
		this.enemies.remove(enemy);
	}, this);
}

I was just about to post this before Lester32 beat me too it! The only thing I would add, is en animation on complete callback, to make sure the enemy and it's associated animations aren't destroyed before the animation is complete.

Link to comment
Share on other sites

this.enemy = enemy;
enemy.destroy();

With this it now disables enemy physics, but does not destroy sprite. If I add sprite keyword between enemy and destroy, it gives error.

rich, please improve collision events in Phaser 3!

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...