Jump to content
This forum will be closing down. Please move to the respective dedicated project forums.

Wrong Sprite in Group being killed


Kraken
 Share

Recommended Posts

I have just started to learn Phaser and I am having a problem with killing sprites. I'm trying to have the enemy sprites die when the player sprite hits the enemy from above. Once it's hit, the enemy will play a dead sprite animation and then be killed after a 1 second timer is completed. I have 4 enemies drop from the top every 5 seconds.

The problem comes when one of the enemies are hit from above, it  will sometimes trigger the incorrect enemy to be killed. Here is some of the code related to the enemy being created and killed.

this.slimePool = this.add.group();
		this.slimePool.enableBody = true;
		for (var i = 0; i < 4; i++){
		this.slimeCreator = this.game.time.events.loop(Phaser.Timer.SECOND * 5, this.createSlime, this);
		}

this.slimePool.forEachAlive(function(element){
		if(element.y >= this.game.height){
			element.kill(); 
		}
	  }, this);

this.game.physics.arcade.collide(this.player, this.slimePool, this.hitEnemy, null, this);

createSlime: function() {
		if(this.player.alive){
			this.slime = this.slimePool.getFirstExists(false);
				
		
		if(!this.slime) {
			this.slime = new Phaser.Sprite(this.game, 0, 0, 'slime');
			this.slimePool.add(this.slime);
			this.slime.animations.add('slimeWalk', [0,1], 3, true);
			this.slime.animations.add('slimeDead', [2], true);
			this.slime.play('slimeWalk');
				
			}
		
		
			this.slime.reset(560 + Math.random() * 600, 0);
			this.slime.body.velocity.x = -275;
			
		
		}
	},
	hitEnemy: function(player, slime) {
        if(slime.body.touching.up){
			this.player.body.velocity.y = -300;
			this.slime.play('slimeDead');
			this.game.time.events.add(Phaser.Timer.SECOND * 1, this.killEnemy, this);
			
		}
		else{
			this.gameOver();
		}
    },
	killEnemy: function() {
			this.slime.kill();
			this.slime.play('slimeWalk');
			
		
    },

   

Link to comment
Share on other sites

When you are creating a slime, you are assigning it to this.slime...

When you collide with ANY slime, this.slime is the one you are killing...

It might be the right one, it might not be...

(slime.body.touching.up){
			this.player.body.velocity.y = -300;
			this.slime.play('slimeDead'); // THIS LINE HERE...
			this.game.time.events.add(Phaser.Timer.SECOND * 1, this.killEnemy, this);
			
		}

Remove this. before slime, and see what happens...

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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