I have a system in place for capturing and registering arrow key input. It works up until a point. It correctly registers if a number of keys are pressed at the same time as long as two or less are pressed. If a third or forth are pressed together it stops firing keydown events. Please see this jsFiddle and view the console's output.
Is it a limitation set in place by the browser or is my code wrong? Any help would be much appreciated.
Here is the code:
var keysPressed = {
37: false,
38: false,
39: false,
40: false
};
var LEFT = 'left';
var RIGHT = 'right';
var UP = 'up';
var DOWN = 'down';
var ON = '_on';
var OFF = '_off'
document.addEventListener('keydown', function(evt){
var keycode = evt.keyCode;
if(!checkKeyPressed(keycode)){
keysPressed[keycode] = true;
switch(keycode){
case 37:
registerInput(LEFT+ON);
break;
case 38:
registerInput(UP+ON);
break;
case 39:
registerInput(RIGHT+ON);
break;
case 40:
registerInput(DOWN+ON);
break;
default:
break;
}
}
});
document.addEventListener('keyup', function(evt){
var keycode = evt.keyCode;
if(checkKeyPressed(keycode)){
keysPressed[keycode] = false;
switch(keycode){
case 37:
registerInput(LEFT+OFF);
break;
case 38:
registerInput(UP+OFF);
break;
case 39:
registerInput(RIGHT+OFF);
break;
case 40:
registerInput(DOWN+OFF);
break;
default:
break;
}
}
});
function checkKeyPressed(keycode){
if (keysPressed === null) {
return false;
} else return keysPressed[keycode];
}
function registerInput(inputType){
console.log(keysPressed);
//Game.Engine.playerInput(inputType);
}
While this isn't necessarily how I would have implemented it, I think your implementation works just fine.
Keep this in mind:
Different keyboards will have different buses for their keys.
On higher quality keyboards, you might get more keys per "area" of the keyboard that can be held at a time...
But depending on what the keyboard is, how the keys are printed, how the regions are divided, et cetera, you're going to have more or less keys which can be used in any given place at a time.
For example, when I play FPS games and similar action games, with my regular mapping, I can't crouch, move forward+left, pull up the leaderboard AND reload at the same time, on my keyboard.
Whatever I do last is going to be ignored.