Search code examples
javaandroidbuttonlibgdxstage

Mutiple stages - Buttons don´t react?


I have 2 Stages in my game with a Table in each one that holds buttons. The first one stores a Table with ingame buttons: move up/down and pause. The second one stores a Table that represents the pause menu. If "pause" is clicked (the game pauses and) I want to draw the second stage that now can process input.

I initialized 2 stages:

public void create(){

...
mainStage = new Stage(viewport,batch);
menuStage = new Stage(viewport,batch);
Gdx.input.setInputProcessor(mainStage);
...

The pause button got an Listener that sets the (enum) STATE to PAUSE (same for the "resume" Button in the pause menu, that sets the state to RUNNING)

pause.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
        thisState = STATE.PAUSE;
        Gdx.input.setInputProzessor(menuStage);

        }
    });

then in the render method

switch (gameState) {
            case RUNNING:

                deltaTime = Gdx.graphics.getDeltaTime();
                stateTime += deltaTime; // for the animations

                Gdx.gl.glClearColor(0, 0, 0, 1);
                Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

                batch.setProjectionMatrix(camera.combined);

                update(deltaTime);

                batch.begin(); 
                ... draws the characters
                batch.end();

                mainStage.act(deltaTime);
                mainStage.draw();
                break;

            case PAUSE:
                Gdx.gl.glClearColor(0, 0, 0, 0.6f); I want the background to become slightly darker.
                Gdx.app.log("Game State","Game is PAUSED");
                menuStage.act(deltaTime);
                menuStage.draw();

        }

If I start the mainStage buttons appear, but aren't clickable. The game stops if I click in the middle of the screen. However, the "pause" button's Listener apparently doesn't even react to that as there was no notification on the console that the game is paused, nor that the button was clicked.

My Start Screen uses only one Stage and works perfectly with the same setup.

What I think the reasons might be:

  • I used setInputProcessor falsely
  • I used Viewport falsely (and resize)
  • I have to somehow let the first stage disappear before drawing a new stage

Solution

  • by your code, gdx is only processing inputs for mainStage, you could swap input processors when showing the menu or use a input multiplexer like this:

    public void create(){
    
    [...]
    mainStage = new Stage(viewport,batch);
    menuStage = new Stage(viewport,batch);
    InputMultiplexer multiplexer = new InputMultiplexer();
    multiplexer.addProcessor(mainStage);
    multiplexer.addProcessor(menuStage);
    Gdx.input.setInputProcessor(multiplexer);
    [...]
    
    }