同时收听多个按键事件

时间:2015-11-08 01:53:05

标签: javascript html5 canvas

好吧,我正在开发Agar的简单克隆,但只有2名玩家。我已经掌握了大部分基本功能,除了我无法弄清楚如何同时处理来自两个玩家的按键事件。 (一次只能移动一个)这是jsFiddle。相关摘要:

if (keysArr.toString() === "37,87") {
    player.dir = "left";
    player2.dir = "up";
    keys = [];
} 

if (keysArr.toString() === "38,87") {
    player.dir = "up";
    player2.dir = "up";
}

if (keysArr.toString() === "39,87") {
    player.dir = "right";
    player2.dir = "up";
}

if (keysArr.toString() === "40,87") {
    player.dir = "down";
    player2.dir = "up";
} 

if (keysArr.toString() === "37,65") {
    player.dir = "left";
    player2.dir = "left";
} 

if (keysArr.toString() === "38,65") {
    player.dir = "up";
    player2.dir = "left";
} 

if (keysArr.toString() === "39,65") {
    player.dir = "right";
    player2.dir = "left";
} 

if (keysArr.toString() === "40,65") {
    player.dir = "down";
    player2.dir = "left";
} 

if (keysArr.toString() === "37,83") {
    player.dir = "left";
    player2.dir = "down";
} 

if (keysArr.toString() === "38,83") {
    player.dir = "up";
    player2.dir = "down";
} 

if (keysArr.toString() === "39,83") {
    player.dir = "right";
    player2.dir = "down";
} 

if (keysArr.toString() === "40,83") {
    player.dir = "down";
    player2.dir = "down";
} 

if (keysArr.toString() === "37,68") {
    player.dir = "left";
    player2.dir = "right";
} 

if (keysArr.toString() === "38,68") {
    player.dir = "up";
    player2.dir = "right";
} 

if (keysArr.toString() === "39,68") {
    player.dir = "right";
    player2.dir = "right";
} 

if (keysArr.toString() === "40,68") {
    player.dir = "down";
    player2.dir = "right";
} 

if (keysArr.toString() === "37") {
    player.dir = "left";
} 

if (keysArr.toString() === "38") {
    player.dir = "up";
} 

if (keysArr.toString() === "39") {
    player.dir = "right";
} 

if (keysArr.toString() === "40") {
    player.dir = "down";
}

我无法找到另一种方式,所以我只是使用了一堆if。

所以,这段代码允许两个玩家同时移动,但在最初的玩家之后,他们无法再次转向。我怎样才能这样做,以便两者同时移动并在之后转动?

1 个答案:

答案 0 :(得分:1)

正在检测第一个被按下时按下的第二个键,因为另一个玩家将移动。

你必须将所有的ELSEIF改为简单的IF。如果玩家1按下一个键,它将永远不会进入玩家2的elseif条件,将玩家2 elseif与玩家1联系起来。这将解决您的主要问题。

document.onkeydown和document.onkeyup监听器不需要每次重复初始化,只需要一次。

我修改了你的jsFiddle来反映这些变化。然后我被带走了,并将代码放在document.onkeyup中,让玩家停止移动,因为它困扰着我。请享用! https://jsfiddle.net/wtqk7Lu2/1/

if (player2.dir === keys.w) {
    player2.y -= player2.speed.y;
}
if (player.dir === keys.up) {
    player.y -= player.speed.y;
}
if (player2.dir === keys.a) {
    player2X -= player2.speed.x;
}
if (player.dir === keys.left) {
    player1X -= player.speed.x;
}
if (player2.dir === keys.s) {
    player2.y += player2.speed.y;
}
if (player.dir === keys.down) {
    player.y += player.speed.y;
}
if (player2.dir === keys.d) {
    player2X += player2.speed.x;
}
if (player.dir === keys.right) {
    player1X += player.speed.x;
}