Skip to content Skip to sidebar Skip to footer

Javascript Movement On Key Hold

I need help with a movement function for a canvas game. Below is what I have, and what happens is the player only changes direction when a left/right key is pressed. It would be i

Solution 1:

Depreciated keyEvent.keyCode do not use.

Please note that keyEvent.keyCode has been depreciated and should not be used. You can use keyEvent.key or keyEvent.code where key is what the user intends to see (holds shift or capslock for "A", or not for "a") and code is for the key location where code is always 'KeyA' no matter if capital or not.

MDN keyboardevent for full details

Use a keyState object

The easiest way I have found to use the keyboard in animations and games is to have a object of key states. Add the same simple event to both down and up

document.addEventListener("keydown",keyhandler);
document.addEventListener("keyup",keyhandler);

Create key state object

var keyState = {};

And then just flag the key depending on the input event

functionkeyHandler(e){  // simple but powerful
   keyState[e.code] = e.type === "keydown";
}

Then in the main loop all you have to do to know if a key is down

if(keyState.ArrowRight) { // right  is down }if(keyState.LeftRight) { // left  is down }

Detailed state

Never do any input processing in IO events when you have a running loop..

You can get more info. I usually have a toggle, and a state change

keyState = {
   down : {},   // True if key is down
   toggle : {},  // toggles on key up
   changed : {},  // True if key state changes. Does not set back false// or you will lose a change
} 

function keyHandler(e){  // simple but powerfulif(keyState.down[e.code] !== (e.type === "keydown")){
       keyState.changed = true;
   }
   keyState.down[e.code] = e.type === "keydown";
   if(e.type === "keyup"){
       keyState.toggle[e.code] = !keyState.toggle[e.code];
   }
}

Now if you want to know if a key has just been pressed

if(keyState.down.LeftArrow && keyState.changed.LeftArrow){
      // key has been pushed down since last time we checked.
 }
 keyState.changed.LeftArrow = false; // Clear it  so we can detect next change

Solution 2:

you can add a while loop:

while(left == true) {
//code to execute
}

I'm not sure if this will work but you can try it.

Solution 3:

You need to have a global event listen and track the pressdown then save the movement somewhere. Check what i've done here https://github.com/panvourtsis/HTML5-canvas-game---POKEMON-/blob/master/canvas.pokemon.js

Also check this

document.onkeydown = function(e) {
        e = e || window.event;

        if(e.keyCode == "37") console.log("left");
        elseif(e.keyCode == "38") console.log("up");
        elseif(e.keyCode == "39") console.log("right");
        elseif(e.keyCode == "40") console.log("down");
    };

Post a Comment for "Javascript Movement On Key Hold"