So my character div changes its background image when the player presses x which then kills the enemy if the character is touching the enemy. This image switch is to do a mock animation of swinging a sword.
I used set timeout to delay switching the background image back to its original state. This works.
HOWEVER theirs a bug where if I spam x there is no longer a delay between the images switching and I hypothesize the reason having something to do with stacking asynchronous callbacks from the setTimeout function that gets invoked when the player spams x.
** SET TIMEOUT INVOKED IN THIS FUNCTION **
function pressOn(e) {
e.preventDefault();
let tempKey = (e.key == " ") ? "space" : e.key;
keys[tempKey] = true;
if (keys['x'] && player.swing == false){
player.plane.style.backgroundImage ='url(guts2.png)';
setTimeout(function () {
player.swing = true;
}, 300);
}
}
** REVERTS BACKGROUND IMAGE TO ORIGINAL **
function playGame() {
if (player.inplay) {
if (player.swing && !keys['x']){
player.plane.style.backgroundImage ='url(guts1.png)';
player.swing = false;
}
window.requestAnimationFrame(playGame);
}
}
** LINK TO JS FIDDLE FULL PROJECT **