I'm trying to create a game in HTML5 and I've come to the point where I need to enable keyboard input.
So Here's my code:
window.addEventListener('keydown', function(e) {
let key = e.keyCode;
console.log(key);
if (key == 37) {
canvas.player.x -= 5;
}
if (key == 38) {
canvas.player.y -= 5;
}
if (key == 39) {
canvas.player.x += 5;
}
if (key == 40) {
canvas.player.y += 5;
}
}, false);
Where canvas
is the canvas object and canvas.player
the player object. It works, but not very well... Let's say I'm pressing (and holding down) the right arrow key (39) and than press the down arrow key (40) the player is not moving to the right anymore since we last pressed the down arrow key. Works fine. Until I only release the down arrow key while still pressing down the right arrow key. So I never released the right arrow key. Than the player stops and the browser doesn't seem to understand that I'm pressing the right arrow key.
You can easily see this in the console log of this fiddle.
Does anybody has a solution for this problem? A way to detect the keycode anyways?