1
\$\begingroup\$

I'm writing a simple game in JavaScript, which already handles basic keyboard input like so:

var input = {};
while (!done) {
    handleInput(input);
    update();
    render();
}

document.onkeydown = function(e) {
    input[e.keyCode] = true;
}
document.onkeyup = function(e) {
    input[e.keyCode] = false;
}

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.

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?

\$\endgroup\$
  • \$\begingroup\$ My suggestion is that since this question is not specific to game developing (i.e. implementation of "key up" in java, especially for the context of setting up multi-key commands, could just as easily be found in other implementations of software development), this would be a better question for Stack Exchange. Not being a game-specific question could make your question off-topic, but SE will also likely give you a better answer. \$\endgroup\$ – Gnemlock Sep 2 '16 at 14:26
  • \$\begingroup\$ @Gnemlock do you think so? I thought I'd ask it here because problems of input buffering and polling in a loop are so typical of game loop implementations IMHO \$\endgroup\$ – Marco Bolis Sep 2 '16 at 20:07
2
\$\begingroup\$

It sounds like you need a enum for state rather than boolean. My suggestion is something like [NONE (or something else), PRESSED, HELD, RELEASED]. And in the game loop create a function to switch any keys that are pressed to held and any keys that are released to none.
Also you might run into issues (especially with this implementation) where your input changes mid handleInput() and I suggest adding a queue to "lock" input to the beginning or end of the loop.

\$\endgroup\$
  • \$\begingroup\$ This is definitely a good idea. What do you mean by "your input changes mid handleInput()"? JS runs single thread all the time... \$\endgroup\$ – Marco Bolis Sep 2 '16 at 19:23
  • \$\begingroup\$ Right, I forgot JS does that. In that case nothing to worry about. \$\endgroup\$ – ndenarodev Sep 2 '16 at 19:27
  • \$\begingroup\$ You know, this answer is so simple I would never think of it :-) Of course it leaves a little bit of pattern checking to be done on the handleInput side, but I think I can cope with it \$\endgroup\$ – Marco Bolis Sep 2 '16 at 20:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.