Javascript movement on key hold

橙三吉。 提交于 2019-12-11 02:01:08

问题


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 ideal for the player to face the corresponding direction from holding down either the left or right arrow keys, which currently doesn't occur.

I have no idea how to do this, any ideas?

I now have movement direction working on key hold down, updated below, but when the page first loads, the player is not displayed on the screen, but then displays after a key is pressed. Something is not right...

var trackRight = 0;
var trackLeft = 1;
var x = 570;
var y = 255; //no collision past here
var srcX;
var srcY;
var speed = 25;

var character = new Image();
character.src = "ptera_purple.png";

function updateFrame() {
    curFrame = ++curFrame % frameCount;
    srcX = curFrame * width;
    ctx.clearRect(0, 0, canvas.width, canvas.height, x, y, width, height);


    if (left && x > 0) {
        srcY = trackLeft * height; //important for sprite direction
        x -= speed;
    }

    if (right && x < canvasWidth - width) {
        srcY = trackRight * height;
        x += speed;
    }
}

var right = false;
var left = false;

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
    if (e.keyCode == 39) {
        right = true;
    } else if (e.keyCode == 37) {
        left = true;
    }
}

function keyUpHandler(e) {
    if (e.keyCode == 39) {
        right = false;
    } else if (e.keyCode == 37) {
        left = false;
    }
}

function moveLeft() { // keyboard controls
    left = true;
    right = false;
}

function moveRight() {
    left = false;
    right = true;
}

回答1:


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.




回答2:


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");
        else if(e.keyCode == "38") console.log("up");
        else if(e.keyCode == "39") console.log("right");
        else if(e.keyCode == "40") console.log("down");
    };



回答3:


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

function keyHandler(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 powerful
   if(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


来源:https://stackoverflow.com/questions/39952551/javascript-movement-on-key-hold

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!