I am making a Snake game using HTML and javascript. The game works by pressing arrow keys to move the snake. It works fine 90% of the time. However, sometimes when I input 2 keys very fast, only one key is registered. For example, if I press the Up and Left button with <10ms delay, the snake will only go Up and not left.
I'm not sure why this is happening so I don't know where to start fixing.
My event listener:
window.onkeydown = function (e){
var keys = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
}
var dx = 0;
var dy = 0;
switch (keys[e.keyCode]){
case 'left':
dx = -1;
break;
case 'up':
dy = 1;
break;
case 'down':
dy = -1;
break;
case 'right':
dx = 1;
break;
default:
return;
}
Is it possible that my issue will be fixed by changing it to addEventListener?
Another theory I have is that the browser thinks I am inputting 2 keys at the same time, so I'd have to code it to queue the inputs.
Or perhaps Javascript doesn't read inputs when it is doing logic?
Can anyone give me a hint?