I have this game loop where I have a red rectangle and a yellow rectangle on top of it. When a player takes damage, the yellow rectangle's width decreases because it is based on player's life. When player's life reaches zero he loses the game and all animations are cancelled. The issue I am having is that because the loop is so quick, the yellow rectangle does not have time to lower the life to zero and a bit of it is left on the screen when the animations are cancelled. For that reason I need to add a bit of delay before cancelling the animations. Thanks guys.
// DECREASE PLAYER LIFE AND DELETE ENEMY IF IT COLIDES WITH PLAYER
enemyArray.forEach(function(enemy) {
if (collides(player, enemy)) {
player.life += -10;
enemy.delete();
}
});
// ANIMATION LOOP
function animate(currentTime) {
const animation = requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
// PLAYER LIFE
// RED REC
c.beginPath();
c.rect(20, 20, 150, 30);
c.fillStyle = "red";
c.fillRect(10, 30, 200, 20);
// YELLOW REC
c.beginPath();
c.rect(20, 20, 150, 30);
c.fillStyle = "yellow";
c.fillRect(10, 30, player.life, 20);
// END GAME
//I need some delay here so that fillRect has time to decrease the yellow bar to 0;
if (player.life <= 0) {
console.log("You Lose");
music.pause();
paused = true;
cancelAnimationFrame(animation);
}
}
animate();
Image of player life bar when animations are canceled. There is a bit left still.