Well, when you hold a key on your keyboard, after the first fire there is a 1sec delay.
You can go ahead and open notepad and hold a key (e.x \'x\') you\'ll see after
Instead, listen for when the key is first pressed, and then listen for when it's released. This also means that you have to record the current state of movement speed somewhereso you can apply it between those events.
This example will only server for walking forward, it should be easy to extend to the other directions.
var playerSpeed = 0;
document.onkeydown = keyDown;
document.onkeyup = keyUp;
function keyDown(e) {
switch(e.keyCode) {
case 38: // UP
playerSpeed = 1; // moving!
break;
// other cases...
}
}
function keyUp(e) {
switch(e.keyCode) {
case 38: // UP
playerSpeed = 0; // NOT moving!
break;
// other cases...
}
}
// Whatever loop is called for each frame or game tick
function updateLoop() {
// rendering, updating, whatever, per frame
Player.PositionY += playerSpeed;
}
This way, it doesn't matter what the repeat rate of the keyboard is. Every onkeydown
, will always eventually have an onkeyup
. All you have to do and update things a different way inbetween those events.
You're lucky, I just code this for a game.
Controller = {
keyIsDown: [],
// Add a new control. up is optional.
// It avoids key repetitions
add: function (key, down, up) {
$(document).keydown(function(e) {
if(e.keyCode === key && !Controller.keyIsDown[key]) {
down()
Controller.keyIsDown[key] = true
return false
}
})
$(document).keyup(function(e) {
if(e.keyCode === key) {
if(up) up()
Controller.keyIsDown[key] = false
return false
}
})
},
}
Example:
Controller.add(65,
function () {
console.log("A is down")
},
// This argument is optional
function () {
console.log("A is up")
})
you could start an event on keydown
and stop it on keyup
$('#mycanvas').on('keydown', function() {
$(document).trigger('start');
});
$('#mycanvas').on('keyup', function() {
$(document).trigger('stop');
});
$(document).on('start', startAnimation);
$(document).on('stop', stopAnimation);
function startAnimation(e) { //start something }
function stopAnimation(e) { //stop something }