I have an animation for a game that I am working on that won't seem to repeat. When the space bar is pressed, it triggers an event that "shoots" a circle to the top of a canvas. The problem is that when the key is pressed again it will not initiate the animation. Here is the sample code that I wrote:
var canvas, ctx,
spaceKey = false,
upKey = false,
downKey = false,
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
shotX = 150, shotY = 280;
function loop() {
if (spaceKey) shoot();
}
function keyDown(e) {
if (e.keyCode == 32) spaceKey = true;
}
function keyUp(e) {
if (e.keyCode == 32) spaceKey = false;
}
function shoot() {
setTimeout(function() { if (shotY > 0) {
ctx.clearRect(shotX-5,shotY-5,600,20);
ctx.beginPath();
ctx.arc(shotX, shotY,4,0,Math.PI * 2, false);
ctx.fillStyle = "yellow";
ctx.fill();
ctx.closePath();
shotY = shotY - 1;
shoot();
} else
ctx.clearRect(shotX-5,shotY-5,600,20);
}, 100);
}
(function init() {
setInterval(loop, 10);
document.addEventListener('keydown', keyDown, false);
document.addEventListener('keyup', keyUp, false);
})();
//init();
The reason I use keyUp
and keyDown
is because I have other functions that use different keys. This code was modified to show only this feature. To make it easier to see what I'm talking about, I created a JSFiddle. The other features I have are similarly structured and work, the only difference being that its duration isn't directly controlled by a key press.