I'm going through Gustavo Steigert's tutorials on libgdx, but I have a feeling that this is more of a design question, rather than specifically regarding libgdx. My question is regarding the splash screen. I can implement what he has in that tutorial without any errors, but I want to add a little extra. In every game I've ever played, the splash screen goes away when the user left-clicks or presses esc, so I'm trying to add that (strangely, I can't find any tutorials with splashes like that). So, I have this method in my SplashScreen
class:
public boolean handleInput() {
if (Gdx.input.justTouched()) {
game.setScreen(new MenuScreen(game));
return true;
} else {
return false;
}
}
At first, I tried to make that method return void
and simply call splash.handleInput()
in the render()
method of the main Game class, Tyrian
. However, that doesn't work, because once the splash screen has been moved on from, handleInput()
will still be called on every render()
, and the game crashes if the user clicks a menu button. So, I made handleInput()
return a boolean and used this code in render()
:
if (onSplash) {
if (splash.handleInput()) {
onSplash = false;
}
}
onSplash
is a boolean inside the Tyrian
class that is true by default.
Something else odd: when using the void
version of handleInput()
, the game will only crash if a button on the menu (the menu screen is the next screen) is pressed., and not if the screen is pressed. I am worried that the splash screen is never being disposed of (though my current solution does not seem to show that), because I can see from logging messages being printed to the console that the menu screen is being created upon every screen click, which is what handleInput()
does. Also, if I put an else
to that code above, with splash.dispose();
as a result, the game will crash.
This is such a common action in games, I would be surprised if there was not a common and cleaner accepted way of implementing it that I have missed.
EDIT: I have changed the handleInput()
back to void
and have used the instanceof
keyword in my main game file. It's a cleaner solution, but I'm not sure if it's the best (it's an extra check on every render!).
SplashScreen.java
public void handleInput() {
if (Gdx.input.justTouched() || Gdx.input.isKeyPressed(Input.Keys.ESCAPE)) {
game.setScreen(new MenuScreen(game));
}
}
Tyrian.java
if (this.getScreen() instanceof SplashScreen) {
splash.handleInput();
}