Currently, I am learning JavaScript and facing an issue. The spaceship in my game is not moving despite no error being present. Pressing the key w
on my keyboard does not trigger any action. I suspect that the problem lies within the line
"document.onekeydown =function(e) {"
, but I am unsure of the exact issue.
let KEY_SPACE = false;
let KEY_W = false;
let KEY_S = false;
let canvas;
let ctx;
let backgroundImage = new Image();
let spaceship = {
x: 50,
y: 200,
width: 100,
height: 100,
src: 'img/spaceship.png'
};
let rock = {
x: 100,
y: 200,
width: 200,
height: 80,
src: 'img/rock.png'
};
document.onekeydown = function(e) {
console.log(e.keyCode);
if (e.keyCode == 32) {
KEY_SPACE = true;
}
if (e.keyCode == 87) { ** THE ISSUE MIGHT BE HERE... **
KEY_W = true;
}
if (e.keyCode == 83) {
KEY_S = true;
}
};
document.onekeyup = function(e) {
console.log(e.keyCode);
if (e.keyCode == 32) {
KEY_SPACE = false;
}
if (e.keyCode == 87) {
KEY_W = false;
}
if (e.keyCode == 83) {
KEY_S = false;
}
};
function startgame() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
loadImages();
draw();
setInterval(function update() {
if (KEY_W) {
spaceship.y -= 1;
}
if (KEY_S) {
spaceship.y = 1;
}
console.log("Hi");
}, 1000);
}
function loadImages() {
backgroundImage.src = 'img/bg.png';
spaceship.img = new Image();
spaceship.img.src = spaceship.src;
rock.img = new Image();
rock.img.src = rock.src;
}
function draw() {
requestAnimationFrame(draw);
ctx.drawImage(backgroundImage, -100, 0, 874, 562);
ctx.drawImage(spaceship.img, spaceship.x, spaceship.y, spaceship.width, spaceship.height);
}
canvas {
background-color: darkgrey;
}
<body onload="startgame()">
<canvas id="canvas" width=" 720" height="480"></canvas>
</body>