gpt4 book ai didi

JavaFX AnimationTimer 未正确停止

转载 作者:行者123 更新时间:2023-12-02 02:30:50 32 4
gpt4 key购买 nike

所以,我正在使用 JavaFX 创建贪吃蛇游戏,但我似乎无法使游戏正确暂停,即它偶尔会暂停,而其他时候,游戏只是忽略暂停。所以,基本上我有一个 Main 类,我在其中初始化所有 GUI 组件,并且它还充当 javafx 应用程序的 Controller 。

我有一个名为 gameControlButton 来启动/暂停游戏,还有一个变量 Boolean Pause 用来跟踪游戏状态(新/paused/running),以及方法 startGamepauseGame

gameControl按钮的EventHandler如下:

gameControl.setOnClicked(event->{
if(paused == null) startGame(); //new game
else if(paused) continueGame(); //for paused game
else pauseGame(); //for running game
});

startGame 函数看起来像这样:

void startGame(){
paused = false;
Snake snake = new Snake(); //the snake sprite
//following gameLoop controls the animation of the snake
gameLoop = new AnimationTimer(){
@Override
public void handle(long now){
drawSnake(); //draws the snake on the game
snake.move(); //move snake ahead

//following code is for slowing down the gameLoop renders to make it easier to play
Task<Void> sleeper = new Task<>(){
@Override
protected Void call() throws Exception {
gameLoop.stop();
Thread.sleep(30);
gameLoop.start();
return null;
}
};
new Thread(sleeper).start();
//force garbage collection or else throws a bunch of exceptions after a while of running.
//not sure of the cause...
System.gc();
}
};
gameLoop.start();
}

AnimationTimer gameLoop 是类的变量,允许从其他函数调用。

以及pauseGame函数:

void pauseGame() {
paused = true;
gameLoop.stop();
}

所以,正如我之前所说,每次我点击 gameControl 按钮时游戏都不会暂停,我怀疑这是由于 Thread.sleep(30); code> 行位于 gameLoopTask 内。话虽这么说,我仍然不完全确定,也不知道如何解决这个问题。任何帮助将不胜感激。

最佳答案

“暂停”是什么类型?您检查它是否为空,然后将其视为 boolean 值。我不明白为什么它会是一个大的“B” boolean 对象包装器而不是原始 boolean 类型。

这个:

        //following code is for slowing down the gameLoop renders to make it easier to play
Task<Void> sleeper = new Task<>(){
@Override
protected Void call() throws Exception {
gameLoop.stop();
Thread.sleep(30);
gameLoop.start();
return null;
}
};

这是一种绝对可怕的限制速度的方法。让你的游戏循环运行,检查每个循环的时间,看看是否已经过去了足够的时间来更新内容。您的动画计时器将驱动游戏。您不想暂停主平台线程,也不想暂停任何正在处理任务的工作线程。如果您正在安排任务,请将它们安排为按照您想要的时间间隔运行 - 不要在 call() 方法中限制线程。

你真正想要的是这样的:

//following gameLoop controls the animation of the snake
gameLoop = new AnimationTimer(){
@Override
public void handle(long now){
if ((now - lastTime) > updateIterval) {
drawSnake(); //draws the snake on the game
snake.move(); //move snake ahead
lastTime = now;
}

您甚至可以将其设置为一个循环来“ catch ”,以防动画计时器由于某种原因落后:

        while ((now - lastTime) > updateIterval) {
drawSnake(); //draws the snake on the game
snake.move(); //move snake ahead
lastTime += updateIterval;
}

关于JavaFX AnimationTimer 未正确停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65061944/

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