Jump to content

looping problem when player hits on enemy


erich
 Share

Recommended Posts

Hi

I have a script that I wish to implement so that if the player hits an enemy 3 times the game restarts, but it constally loops when touching, where am I going wrong ??

create function

this.currentHits = 3;
this.collisionHasOccurred = false;

update function :

this.game.physics.arcade.overlap(this.player, this.enemies, this.youLose, null, this);

youlose function :

youLose : function(player, enemies){
        
        if (!this.collisionHasOccurred)
        {
            this.currentHits --;
            this.collisionHasOccurred = true;
        } else {
            this.collisionHasOccurred = false;    
        }
            console.log(this.currentHits);
            console.log(this.collisionHasOccurred);

        if (this.currentHits === 0)
        {
            //this.game.state.start('Game');
            console.log('GAME OVER');
        }     
  },

thanks in advance

eric

 

Link to comment
Share on other sites

@erich You have the right idea but for any overlap longer than 2 frames (very likely) `collisionHasOccurred` will be flipping back and forth and the player will still accrue hits.

You can use a timer:

// @create:

this.currentHits = 3;
this.setPlayerCanCollide();

// @update:

if (this.playerCanCollide) {
    this.game.physics.arcade.overlap(this.player, this.enemies, this.youLose, null, this);
}

// …

setPlayerCanCollide: function() {
    this.playerCanCollide = true;
}

youLose: function(player, enemies) {

    this.currentHits--;
    this.playerCanCollide = false;
    this.time.events.add(1000, this.setPlayerCanCollide, this);
    
    // …
}

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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