How to change Screens in Scene2D libGDX

Chris picture Chris · Sep 4, 2013 · Viewed 8.9k times · Source

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);

    }

}

Answer

Micah Carrick picture Micah Carrick · Sep 5, 2013

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.