I'm trying to develop a game using CraftyJS. I'm using
I'm noticing some oddities in how keyboard events are being handled. I'm guessing that a lot of this has to do with Chrome or maybe even my physical keyboard, and that Crafty is only relevant in that I'm using it's API.
First, here's my SSCCE. This code adds a key to the keys array when it's pressed, removes it when it's released, and logs out the array every second.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>keyTest</title>
<script src="../crafty.js"></script>
<script>
window.onload = function(){
Crafty.init(window.innerWidth, window.innerHeight, document.getElementById('game'));
var keys = [];
var keyDown = function(e){
console.log("KeyDown " + e.key);
keys.push(e.key);
};
var keyUp = function(e){
console.log("KeyUp " + e.key);
keys.splice(keys.indexOf(e.key), 1);
};
Crafty.e("Keyboard").bind("KeyUp", keyUp).bind("KeyDown", keyDown);
Crafty.e("Delay").delay(function(){console.log(keys)}, 1000, -1);
};
</script>
</head>
<body>
<div id="game"></div>
</body>
</html>
I'm noticing some odd behavior:
First, It looks like Crafty will only recognize four letter-key presses at once, unless they can be typed using both the right and left hand. For example holding down ASDFE at once results in: [65, 83, 68, 70]
The E key remains unrecognized no matter how much I bash on it. But, if for example I hold down ASDFJKL, then I see: [65, 83, 68, 70, 74, 75, 76]
.
Only two arrow keys will be recognized at once unless the third one is the down arrow. For example pressing LEFT, UP, RIGHT results in: [37, 38]
But LEFT DOWN RIGHT results in: [37, 39, 40]
What on earth is up with this? My guess is that someone between my fingers and my JS is trying to cleverly correct for errant key presses (typos), but I don't know who, and I don't know what rules govern this.
EDIT: I suspect that it's my keyboard itself (or the OS) that is failing to send these keyboard events. But I'm still looking for a good way to confirm this.
As @David has figured out, the issue is called keyboard ghosting:
"Ghosting" is the problem that some keyboard keys don't work when multiple keys are pressed simultaneously. The key presses that don't show up on the computer or seem to have disappeared are said to have been "ghosted". On most keyboards, even some that are explicitly marketed as "Anti-Ghosting," this happens with many three key combinations. Imagine playing your favorite video game and not being able to, say, run diagonally and fire your weapon at the same time (say pressing a, w, and g simultaneously). This is a result of the internal design of most existing keyboards...
Since not every consumer has a gaming keyboard (which particularly don't suffer from this issue), I guess the only thing you can do is to design your game around not requiring pressing three or more keys at the same time.