Reputation: 2465
I've been searching around Google for tutorials on how to use multiple screens with LibGDX using Scene2D. So far this is what I have in my Scene handling class but I don't know where to go from here. I know I have to do something to the constructor of MainMenu.java
but I don't know what it is.
What I've got so far:
public class ScreenHandler extends Game{
public MainMenu Main;
@Override
public void create() {
Main= new MainMenu();
setScreen(Main);
}
}
Upvotes: 3
Views: 9078
Reputation: 56
I know this is old, but just want to point out that accepted answer WILL NOT render; just got tied up on this for 2 hrs...
// ...
@Override
public void render() {
AbstractScreen currentScreen = (AbstractScreen) getScreen();
if (currentScreen.goBack) {
setScreen(currentScreen.getBackScreen());
} else if (currentScreen.goToNextScreen) {
setScreen(currentScreen.getNextScreen());
}
}
You MUST add a call to super.render() in a Game subclass if you override Game's render() method.
Upvotes: 4
Reputation: 10187
I'm not a big fan of making my screen classes coupled to my Game class. The approach that I'm using is an abstract class for all of my game's screens which has a a flag and functionality to indicate that a "next screen" is being requested. The render
method of my Game class can then check for that flag and render a new screen accordingly.
public class MyGame extends Game {
// ...
@Override
public void create() {
GameScreen screen1 = new GameScreen(); // extends AbstractScreen
GameScreen screen2 = new GameScreen(); // extends AbstractScreen
screen1.setNextScreen(screen2);
screen2.setBackScreen(screen1);
}
@Override
public void render() {
AbstractScreen currentScreen = (AbstractScreen) getScreen();
if (currentScreen.goBack) {
setScreen(currentScreen.getBackScreen());
} else if (currentScreen.goToNextScreen) {
setScreen(currentScreen.getNextScreen());
}
}
In practice I wouldn't actually instantiate all the screens in the create
method but instead have methods for creating/disposing screens as needed, but, the above is a simplification of the general idea.
Then the individual screens are responsible for setting the goBack
and goToNextScreen
flags as necessary.
Upvotes: 6