3noki
3noki

Reputation: 397

Check Collision function is matching on 2 objects in same location

Full code here

I've noticed if there are two bugs in the same location and the player collides, it counts two deaths as it's technically colliding with two different objects, How can I change this to check collision 1 at a time, or only count 1 death?

checkCollision(playerl,playerr) {
  //check collision for each bug
  for (var i = 0; i < 5; i++) {
        var thisEnemy = allEnemies[i];
        if (
           thisEnemy.leftLimit < player.rightLimit &&
           thisEnemy.rightLimit > player.leftLimit &&
           thisEnemy.upperLimit > player.lowerLimit &&
           thisEnemy.lowerLimit < player.upperLimit) {
           console.log("collision");
           //console.log(player.lowerLimit, player.upperLimit, thisEnemy.lowerLimit, thisEnemy.upperLimit)
          player.loseLife();
       }
    }
};

Upvotes: 0

Views: 28

Answers (1)

bug56
bug56

Reputation: 154

Why not use a setTimeout to implement a short period of invincibility after dying once?

//somewhere in your code
var dying = false;

checkCollision(playerl,playerr) {
  //check collision for each bug
  for (var i = 0; i < 5; i++) {
        var thisEnemy = allEnemies[i];
        if (
            thisEnemy.leftLimit < player.rightLimit &&
            thisEnemy.rightLimit > player.leftLimit &&
            thisEnemy.upperLimit > player.lowerLimit &&
            thisEnemy.lowerLimit < player.upperLimit &&
            dying==false) {

            console.log("collision");
            dying=true; // dying is true, so we wont end up in this block again
            setTimeout(function(){
                dying=false; //after 500 milliseconds we set dying to false so our player has the ability to die again!
            },500);
            player.loseLife();
       }
    }
};

Upvotes: 1

Related Questions