Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smooth keypress event handeling in Javascript?

Tags:

javascript

I know its possible but I cant seem to figure it out. In its basic form I have a canvas circle moving 5 pixels every key event however this seems to be rather slow at firing and really jumpy, plus it stalls when changing key or changing from rapid key press to holding down.

So can someone enlighten me of a way ofwhich this could work without it stuttering?

Thanks.

like image 498
Tom C Avatar asked Dec 16 '22 15:12

Tom C


2 Answers

What you want to do is set variables on keydown and keyup to true or false that you check every tick. Something like this:

var tickRate = 30,
    keyDown = {},
    keyMap = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

$('body').keydown(function(e){ keyDown[keyMap[e.which]] = true;  });
$('body').keyup(function(e){   keyDown[keyMap[e.which]] = false; });

var tick = function() {
  if        (keyDown['up']) {
    // up code
  } else if (keyDown['down']) {
    // down code
  } else if (keyDown['left']) {
    // left code
  } else if (keyDown['right']) {
    // right code
  }

  // other code

  setTimeout(tick, tickRate);
};

tick();
like image 131
mVChr Avatar answered Dec 30 '22 19:12

mVChr


The main problem you have here is that you are at the mercy of the "key repeat" functionality of the Operating System. Usually if you hold a key down, a keyPress event will be generated once, then (after a delay) on a repeat. But if you want to control this delay/repeat, then that's not good enough.

Instead I'd have your own polling function, set to run every few milliseconds, checking whether each key you're interested in is down or up. Then you know that, for every poll whilst the key is down, some event can be fired regardless of the OS's settings.

You can then apply your own algorithms and multipliers to smooth the movement out.

like image 35
Lightness Races in Orbit Avatar answered Dec 30 '22 20:12

Lightness Races in Orbit