Search code examples
javascriptkeyboard-shortcutskeyboard-eventsgame-loop

How to handle keyup events in main game loop?


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:

  • exposing an array containing a list of keyup events (object with "main" key plus modifiers). The handleInput function would be responsible for draining the queue every time it polls it
  • keeping track of possible key combos inside handleInput (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?


Solution

  • 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 = {};
    }
    

    Demo

    Hope that helps!