I'm trying to make a canvas jump. By jumping I mean moving up for a kinda sort time and then going down to the floor again. Something is obviously wrong because nothing happen when I press space. Can't think of what's wrong with my code, any ideas?
var spaceKey = false;
var player = {
side: 20,
x: 0,
y: HEIGHT - 20,
color: "red"
};
context.fillStyle = player.color;
context.fillRect(player.x, player.y, player.side, player.side);
setInterval(update, 1000/60);
function update(){
clearCanvas();
if (spaceKey){
jump();
}
draw();
}
function jump(){
// Moving the player 5 px up 60 times every 10ms.
for (var i = 0; i < 60; i++){
function jumpUp(){
player.y -= 5;
}
setTimeout(10, jumpUp);
}
// Moving the player 5 px down 60 times every 10ms.
for (var i = 0; i < 60; i++){
function jumpDown(){
player.y += 5;
}
setTimeout(10, jumpDown);
}
}
function onKeyDown(evt) {
//Making spaceKey true onclick and calling the jump function.
if (evt.keyCode == 32) spaceKey = true;
}
function onKeyUp(evt) {
if (evt.keyCode == 32) spaceKey = false;
}
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);
(This is not all of my code, and if you want me to add any more code please let me know.)Thanks
