由于您在谈论屏幕,因此我觉得最好将所有逻辑分离到不同的屏幕中。我通常做什么:
定义一个名为screen的接口,并有多个屏幕实现它。像LoadingScreen,MainMenuScreen,GameScreen,GameOverScreen,HighScoreScreen等。在游戏中,您放置了一个保存当前屏幕的变量。在每个循环中,您调用screen.update()并渲染当前屏幕。因为您的状态是由当前屏幕定义的,所以这将为您节省很多“如果此状态就可以这样做”。
这将很好地分隔您的逻辑。
示例代码:
### Screen interface ###
public interface Screen {
public void show();
public void update(float delta);
public void render(float delta);
public void hide ();
}
### An implementation of screen ###
public class MainMenuScreen implements Screen {
private Game game;
public MainMenuScreen(Game game) {
this.game = game;
}
public void show() {
// init stuff
}
public void update(float delta) {
// react to clicks, update animations etc.
if (buttonwasclicked) {
game.setScreen(new GameScreen(game)); // change the screen
}
}
public void render(float delta) {
// draw everything
}
public void hide() {
// release all resources, as the screen is being hidden
}
}
### Game, drawing the appropriate screen ###
public class Game {
public Screen screen;
public void update() {
screen.update(getDeltaTime);
screen.render();
}
public void setScreen(Screen screen) {
this.screen.hide();
this.screen = screen;
this.screen.show();
}
}
或者根据您的游戏设置,您的游戏可能会陷入无限循环。
while(true) {
calculatetimesincelastframe()
screen.update(time);
screen.render(time);
}