5

So I draw an object on the screen at objectx, objecty and increment objectx when right arrow is pressed, moving the object to the right. The problem I'm running into is that if I hold the right arrow key down it increments once, pauses, and then increments repeatedly. My question is why does it do this, and how can I make the object move fluidly without that initial pause?

$(window).keydown(function(e) {
    if(e.keyCode == 39) {
        objectx++;
    }
}
Cains
  • 883
  • 2
  • 13
  • 23
  • That's how keyboards work. I'm pretty sure it's a setting on your OS. Notice how when you type in a textbox (holding down a key, the pause happens) – Ian Aug 14 '13 at 18:20
  • 1
    If you're working on some sort of game that requires keeping track of a lot of keys pressed you might want to store the state of each key in an array, which will eliminate the delay when a key is held down. – Austen Aug 14 '13 at 18:21
  • 2
    duplicate:http://stackoverflow.com/questions/12273451/how-to-fix-delay-in-javascript-keydown – Tomasz Kowalczyk Aug 14 '13 at 18:34

2 Answers2

3

Make an interval that increases the objects, on key down, and stop the interval on keyup. (Save the interval ID somewhere, also make sure to not make the interval twice when it's already there)

Michiel Dral
  • 3,932
  • 1
  • 19
  • 21
  • @Cains I would probably do something like Michiel said. The behavior you described is OS based. So your best bet is to keep/update the key pressed `onkeydown`. Set a variable `pressed` setting `true` or `false` on the events `keydown` and `keyup`, and having a `timer` doing a smoothly animation. – wendelbsilva Aug 14 '13 at 18:29
0

There is nothing wrong with the code - the auto-repeat key behavior is O/S + Browser dependent, and each user will have a different setting for how long a key has to be pressed continuously before it is registered as repeating key press, and at which rate, too. This behavior is intended to avoid errant multiple key presses.

Code-wise, the keyDown event is being captured flawlessly, it is the browser that does not fire those events.

losnir
  • 1,141
  • 9
  • 14