straker / endless-runner-html5-game

An Endless Runner Style HTML5 Canvas Game. Hosts all the files for the two part tutorial series on http://blog.sklambert.com/endless-runner-html5-game/.
78 stars 67 forks source link

Flicker issue #2

Closed dsyenket closed 6 years ago

dsyenket commented 6 years ago

Hi, I changed the updateEnemies function a little bit by removing the gameOver() function if the player collides with enemy and replace it with splice function. However I noticed when the enemy that collides with the player gets removed, the other enemies nearby will have the flicker effect. any idea how to solve this? Thanks.

straker commented 6 years ago

My guess is that you're performing the splice inside the update enemies loop? If you splice during that loop, you'll miss updating one of the enemies in the list. That might be causing the flicker.

enemies = [0,1,2]

for (var i = 0; i < enemies.length; i++) {
  console.log(enemies[i]);   

  if (enemies[i] === 0) enemies.splice(i,1);
}

// => output will be "0" "2"
dsyenket commented 6 years ago

Any idea on how to make the enemy disappear when the player hits the enemy but will not cause it to flicker?

straker commented 6 years ago

If that's the cause of the flicker, you can manually increment i when you don't splice instead of letting the loop do it.

for (var i = 0; i < enemies.length; ) {
  console.log(enemies[i]);

  if (enemies[i] === 0) enemies.splice(i,1);
  else i++;
}
dsyenket commented 6 years ago

This is the function that was used to update enemies position and draw. function updateEnemies() { // animate enemies for (var i = 0; i < enemies.length; i++) { enemies[i].update(); enemies[i].draw();

// player ran into enemy
if (player.minDist(enemies[i]) <= player.width - platformWidth/2) {
  //gameOver();
  if (enemies[i] === 0)
{
    enemies.splice(i, 1);
}
else
{
    i++;
}
}

}

// remove enemies that have gone off screen if (enemies[0] && enemies[0].x < -platformWidth) { enemies.splice(0, 1); } }

It's not removing the enemy as it should.

straker commented 6 years ago

remove the if (enemies[i] === 0) and just leave the enemies.splice(i,1).

dsyenket commented 6 years ago

Thank you very much, it works.