文档 keyup 多任务处理

document keyup multitasking

我正在 javascript 中创建一个小游戏,需要同时按下多个键才能移动化身。

为了识别多次按键,我使用了 "Braden Best" 对问题 JavaScript multiple keys pressed at once 的回答,除了该文档似乎没有处理多任务按键事件之外,它运行良好。例如,如果我想按向上箭头键,然后按向左箭头键,然后释放向左箭头键,头像将完全停止。

这是一个示例代码: https://Jsfiddle.net/552gc9dh/1/

var c = document.getElementById("canv");
var canv = c.getContext("2d");
console.log("test");

var map = {};
var playerlist = [];

function player(width, height, x, y, color, speedx, speedy) {
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    this.color = color;
    this.speedx = speedx;
    this.speedy = speedy;
    playerlist.push(this);
}
var player1 = new player(50, 50, 0, 0, "red", 2, 2);
console.log(playerlist[0]);

function gravity(playerY) {


}

function createplayerlistener(name, key1, key2, key3, key4) {
    onkeydown = onkeyup = function(e) {
        e = e || event;
        map[e.keyCode] = e.type == 'keydown';
        if (name.x + name.speedx < c.width - name.width) {
            if (map[key1]) {
                name.x += name.speedx;
            }
        }
        if (name.x + name.speedx > 0) {

            if (map[key2]) {
                name.x -= name.speedx;
            }
        }
        if (name.y + name.speedy < c.height - name.height) {
            if (map[key3]) {
                name.y += name.speedy;
            }
        }
        if (name.y + name.speedy > 0) {
            if (map[key4]) {
                name.y -= name.speedy;
            }
        }

    }
}
createplayerlistener(player1, 39, 37, 40, 38);


setInterval(function() {

    canv.clearRect(0, 0, c.width, c.height);
    for (var i = 0; i <= playerlist.length - 1; i++) {
        canv.fillStyle = playerlist[i].color; // iterates through players and draws them
        canv.fillRect(playerlist[i].x, playerlist[i].y, playerlist[i].width, playerlist[i].height);
    }
}, 10); 

这个答案更像是一种策略...

我会为方向设置变量并在 keyDownkeyUp

上更新它们

Sudo 代码

const North = false;
const West = false;
const South = false;
const East = false;

keyUp = keyDown = (keyType) {
  switch(keyType) {
    case 'up':
      North = !North;
      break;
    case 'right':
      East = !East;
      break;
    case 'down':
      South = !South;
      break;
    case 'left':
      West = !West;
      break;
  };
} 

setInterval({
  if(North) //move up

  if(South) //move down

  if(East) //Move right

  if(West) //Move left

}, 10);

这应该会保持当前的运动,直到您收到取消它的命令。如果用户按下两者,它还将允许上下或左右相互对抗。

希望这对您有所帮助!


加法

可能更高效的选择实际上是在特定方向的按键按下时创建一个 setInteval 并在按键向上时将其删除,这样如果玩家没有互动,你就不会 运行 额外每 1/100 秒循环一次

directions = {
  up: null,
  right: null,
  down: null,
  left: null
}

const startInterval = (keyType) => {
  direction[keyType] = setInteval(()=> move(keyType);
}
const endInterval = (keyType) => {
  clearInterval( direction[keyType]);
  direction[keyType] = null;
}
const keyUp = keyDown = (keyType) {
  if(direction[keyType] === null) {
    startInteval(keyType);
  } else { 
    endInterval(keyType);
  }
}