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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With