问题描述
按照YouTube上的一些简单教程,我创建了一个简单的蛇游戏。
I created a simple snake game after following some simple tutorials on YouTube.
问题是游戏没有暂停功能(例如,按P时游戏应暂停/继续播放),并且当蛇碰到画布的边框时,游戏会自行重启(但这是另一个问题)。
The problem is that the game does not have a pause function (e.g. when pressing P the game should pause/resume) and when the snake hits the border of the canvas the game restarts itself (but that is another problem).
这是我在游戏中拥有的完整代码:
Here is the complete code I have of the game: https://pastebin.com/URaDxSvF
我创建的与暂停相关的功能:
The pause-related functions I've created:
function gamePaused{ /**i need help on this**/ }
function keyDown(e) {
if (e.keyCode == 80) pauseGame();
}
function pauseGame() {
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(loop, 1000 / 30);
gamePaused = false;
}
}
推荐答案
创建一个布尔值变量,称为suspended,如果玩家按p,则将其设置为true,然后在运行游戏的循环中放置一个if语句。并说出是否(!paused){运行循环}
Create a Boolean variable called paused and set it to true if the player presses p, Then put an if statement around the loop that runs your game. and say if (!paused){run loop}
您可以为按下p时创建一个切换暂停功能。
You can create a toggle pause function for when p is pressed.
function togglePause()
{
if (!paused)
{
paused = true;
} else if (paused)
{
paused= false;
}
}
您还需要创建一个事件何时按下p的侦听器
像这样
You also need to create an event listener for when p is pressedLike this
window.addEventListener('keydown', function (e) {
var key = e.keyCode;
if (key === 80)// p key
{
togglePause();
}
});
在顶部放置游戏对象和常量的状态为paused = false,并在循环函数中
up the top where you have Game objects and constants put in paused = false, and in your loop function do this
draw();
if(!paused)
{
update();
}
这篇关于如何暂停由js和html5制作的简单画布游戏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!