Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Libgdx multiple screens

Thanks to the help I got with my other problems on this forum, I managed to advance my project, but yet another obstacle appears in my way.

I am having trouble implementing multiple Screens in libgdx for java. I would like to know how can I implement multiple screens (one for the main menu, one for play, one for loading screen, ...).

An example or some explanations of how should I structure my screen classes would be really helpful. I tried implementing my own screen manager but that didn't go very well... Also some pointers on how should I dispose screens, since creating screens every time you go from main menu to play or to options menu isn't a very good idea. Any ideas or code example or advice is much appreciated.

What I have now are some classes of game screens which when you render them they will draw some GUI on the screen, but functions like the back button don't work since I don't know how to make the link between them.

like image 990
Andrew Avatar asked May 13 '14 16:05

Andrew


1 Answers

Let's say you got 3 screens, MainMenuScreen, OptionsScreen, GameScreen.

First you need to declare them in your main class.

It will look like this

public class MainClass extends Game implements ApplicationListener {

    private GameScreen gameScreen;
    private MenuScreen menuScreen;
    private OptionsScreen optionsScreen;

    @Override
    public void create() {



    }
    setGameScreen()
    {
        gameScreen=new GameScreen(this);
        setScreen(gameScreen);
    }
    setMenuScreen()
    {
        menuScreen=new menuScreen(this);
        setScreen(menuScreen);
    }
    setOptionsScreen()
    {
        optionsScreen=new OptionsScreen(this);
        setScreen(gameScreen);
    }



    @Override
    public void dispose() {

        super.dispose();
    }

    @Override
    public void render() {

        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        super.render();
    }

    @Override
    public void resize(int width, int height) {

        super.resize(width, height);
    }

    @Override
    public void pause() {
        super.pause();
    }

    @Override
    public void resume() {
        super.resume();
    }
}

Now every screen you got, needs to have a MainClass variable and a constructor of it.

Lets say for the GameScreen class, it will be like

public class GameScreen implements Screen{

    private MainClass mainClass;

    public GameScreen(MainClass mc)
    {
        mainClass=mc;
    }
    // your methods (show,render, pause, etc)
}

Now when you want to change the screen just use in your screen

mainClass.setMenuScreen();
like image 136
Boldijar Paul Avatar answered Sep 27 '22 23:09

Boldijar Paul