I'm writing a simple game in JavaScript, which already handles basic keyboard input like so:
var input = {};
document.onkeydown = function(e) {
input[e.keyCode] = true;
}
document.onkeyup = function(e) {
input[e.keyCode] = false;
}
while (!done) {
handleInput(input);
update();
render();
}
Now I need the game to handle key combos (like CTRL+X for example). I would like it to accept such combos on keyup
only.
EDIT: Modifier keys don't need to go all up at the same time as the "main" key. /EDIT
Two possible solutions that come into my mind are:
keyup
events (object with "main" key plus modifiers). The handleInput
function would be responsible for draining the queue every time it polls ithandleInput
(watching for held down modifier keys) and trigger the combo behavior when the "main" key goes up (I actually don't like this that much)Would you suggest me an elegant way to extend the current functionality?
All you have to do is to create upInput
variable where you will store your keyup keys in. Then, to check if the combo was pressed you have to check if there is only CTRL + C
(or 17, 67) combo in variable and if all of them were true
. Then easily print your message and reset upInput
variable.
var input = upInput = {};
document.onkeydown = function(e) {
input[e.keyCode] = true;
if (JSON.stringify(Object.keys(upInput)) != '["17","67"]')
upInput = {};
}
document.onkeyup = function(e) {
var k = e.keyCode;
input[k] = false;
if ([17, 67].indexOf(k) > -1)
upInput[k] = true;
if (JSON.stringify(Object.keys(upInput)) == '["17","67"]'
&& upInput[17] && upInput[67]) // CTRL + C
alert('YES!'),
upInput = {};
}
Hope that helps!