gpt4 book ai didi

javascript - 同时监听多个按键事件

转载 作者:行者123 更新时间:2023-12-03 08:25:03 25 4
gpt4 key购买 nike

好吧,所以我正在开发 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。

所以,这段代码可以让两个玩家同时移动,但在第一个玩家之后,他们就不能再转动了。我该如何做才能让两者同时移动并随后转动?

最佳答案

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

您必须将所有 ELSEIF 更改为简单的 IF。将玩家 2 elseif 与玩家 1 if 绑定(bind)意味着如果玩家 1 按下某个键,它将永远不会达到玩家 2 的 elseif 条件。这将解决您的主要问题。

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

我修改了您的 jsFiddle 以反射(reflect)这些更改。然后我得意忘形,还将代码放在 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;
}

关于javascript - 同时监听多个按键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33589886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com