4

Well lately i got interested in creating JS games. (not an area i have experience with but it interests me).

i know there are several gaming engines for JS out there but i dont really want to create a game. rather i am curious on how things work / how can i create one.

I have several questions:

  1. Anyone with suggestions on where can I read about it? Prerequisite (what knowledge is needed).

  2. I tried making a small game of something walking in a rectangular. By binding keyup to the window and checking the event.which to get the key that was pressed. I realized that if i clicked on 2 buttons same time only 1 of them is being registered. how can i overcome that?

    $(window).keyup(function(event){
         globalEvent = event.which;
    
    });
    
mpen
  • 272,448
  • 266
  • 850
  • 1,236
Neta Meta
  • 4,001
  • 9
  • 42
  • 67
  • Try using the keydown function instead. That MIGHT overcome the problem of multiple keystrokes. – CodeMouse92 Jan 07 '14 at 00:50
  • 1
    Nah key down doesn't make any difference – Neta Meta Jan 07 '14 at 00:50
  • Just found this similar question: http://stackoverflow.com/questions/5203407/javascript-multiple-keys-pressed-at-once (Not a duplicate) – CodeMouse92 Jan 07 '14 at 00:51
  • possible duplicate of [Detect multiple keys on single keypress event on jQuery](http://stackoverflow.com/questions/10655202/detect-multiple-keys-on-single-keypress-event-on-jquery) – David Mulder Jan 07 '14 at 00:52

2 Answers2

5

To directly answer your second question.

Here is one way:

var keyPressed = {};

$(window).keydown(function(e) {
    keyPressed[e.which] = true;
}).keyup(function(e) {
    keyPressed[e.which] = false;
});

Now you can use keyPressed whenever you want to determine if a key is down:

// wherever
var key1 = 65, key2 = 66; // A and B
if (keyPressed[key1] && keyPressed[key2]) {
    // A and B are both being pressed.
}
itdoesntwork
  • 4,666
  • 3
  • 25
  • 38
  • I see but let for example say someone pressed and hold left, then clicked up while left is still clicked. how will i trigger then next (if) ? does that make sense ? – Neta Meta Jan 07 '14 at 00:58
  • You could attach another `keydown` event and inside that event check if both keys are being pressed through the `keyPressed` object. – itdoesntwork Jan 07 '14 at 01:00
  • I had to add set interval for it to work - unless there's a better way ? Here is an example : http://jsfiddle.net/2Nn9T/2/ – Neta Meta Jan 07 '14 at 04:27
4

In order to detect multiple keys being held down, use the keydown and keyup events.

var keys = {};

$(document).keydown(function (e) {
    keys[e.which] = true;
});

$(document).keyup(function (e) {
    delete keys[e.which];
});
Rohan
  • 3,296
  • 2
  • 32
  • 35