所以我正在制作一个无尽的跑步游戏,并且我制作了一个功能,应该在事件运行时暂停游戏,但是当我尝试玩游戏时,它崩溃/不加载。有谁知道为什么?我还尝试了 if 函数而不是 while 循环,但是当我按下 P
键时,什么也没发生。本质上,如果 PP
布尔值设置为 false,我希望它冻结所有内容。
如果你想测试它,我这里有:https://aakhilv.js.org/endless-runner/
这是我的代码(仅相关部分):
// Booleans
let UP = false;
let DOWN = false;
let HKD = true;
let PP = true;
// Controls
document.onkeydown = function(e) {
if (HKD && e.keyCode == 38) UP = true;
HKD = false;
if (e.keyCode == 40) DOWN = true;
};
document.onkeyup = function(e) {
if (!e.repeat && e.keyCode == 38) UP = false;
if (e.keyCode == 40) DOWN = false;
};
document.onkeypress = function(e) {
if (e.keyCode == 80 && PP) PP = false;
if (e.keyCode == 80 && !PP) PP = true;
};
// Frames
function update() {
// Clear
ctx.clearRect(0, 0, 512, 512);
// Environment
ctx.drawImage(bg, 0, 0);
ctx.drawImage(fl, 0, 384);
ctx.drawImage(fl, 128, 384);
ctx.drawImage(fl, 256, 384);
ctx.drawImage(fl, 384, 384);
ctx.drawImage(cb, 10, 10);
ctx.drawImage(c, 0.5, 0, c.width / 2, c.height / 2);
ctx.font = "40px Font";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillStyle = "#ae7640";
ctx.fillText(0, 55, 15);
// Enemies
if (mx >= -128) {
ctx.drawImage(m, mx -= speed, 256);
} else if (mx <= 0) {
mx = Math.floor(Math.random() * (1024 - 512) + 512);
};
if (bx >= -256) {
ctx.drawImage(b, bx -= speed, 215);
} else if (bx <= 0) {
bx = Math.floor(Math.random() * (1536 - 512) + 512);
};
if (cx >= -384) {
ctx.drawImage(c, cx -= speed, 280);
} else if (cx <= 0) {
cx = Math.floor(Math.random() * (4608 - 512) + 512);
};
while (Math.abs(mx - bx) < 192) {
mx = Math.floor(Math.random() * (1024 - 512) + 512);
bx = Math.floor(Math.random() * (1536 - 512) + 512);
};
// HKD
if (y == 256) {
HKD = true;
};
// UP
if (UP) {
if (y > 100) {
ctx.drawImage(pl, 0, y -= speed);
} else {
UP = false;
};
} else if (!UP) {
if (y < 256) {
ctx.drawImage(pl, 0, y += speed);
} else {
ctx.drawImage(pl, 0, y);
};
};
// DOWN
if (DOWN) {
pl.src = "./Assets/Duck.png";
} else if (!DOWN) {
pl.src = "./Assets/Idle.png";
};
};
while (PP) {
setInterval(update, 10);
};
答案 0 :(得分:1)
while (PP) {
setInterval(update, 10);
};
上面的代码无限调用setInterval,这将创建无限多个间隔。相反,您只想 setInterval
一次,然后在 update
内检查 PP
是否为真,如果为假则跳过函数体。
function update() {
if(PP){
// Clear
ctx.clearRect(0, 0, 512, 512);
// Environment
ctx.drawImage(bg, 0, 0);
// ...
}
};
setInterval(update, 10);
对代码的其他注释:您应该将变量命名为其他人可以理解的名称,并且在结束“}”之后不需要分号。此外,if
不是函数。
答案 1 :(得分:1)
问题可能出在这里 -
document.onkeypress = function(e) {
if (e.keyCode == 80 && PP) PP = false;
if (e.keyCode == 80 && !PP) PP = true;
};
最初 PP = 真
现在如果用户按下“P” 第一个如果条件为真,PP 将被赋值为假;
现在将检查第二个条件,!PP 将解析为 true,因为之前的 if 代码执行,因此 PP 恢复为 true。
您可能想使用 if else 上面的,即
document.onkeypress = function(e) {
if (e.keyCode == 80 && PP) PP = false;
else if (e.keyCode == 80 && !PP) PP = true;
};