michaeljan
michaeljan

Reputation: 301

How to disable a button when switching Screens? (Android LibGDX)

My render method:

public void render(float delta) {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    int w = GateRunner.WIDTH;
    int h = GateRunner.HEIGHT;

    cam.update();
    cam.setToOrtho(false, w, h);

    Gdx.input.setInputProcessor(this);

    game.batch.begin();

    game.batch.draw(title_background, 0, 0, GateRunner.WIDTH, GateRunner.HEIGHT);
    game.batch.draw(title, (w / 2) - (w / 2), h / 2 + h * 12 / 90, w, (int) (w * 0.5));

    playButtonSprite.setPosition((w / 2) - (w / 2), h / 2 + h / 20);
    playButtonSprite.setSize(w, (int) (w * (144.0 / 1080)));
    playButtonSprite.draw(game.batch);

    game.batch.draw(instructions_button, (w/2) - (w/2), h/2 + h/20 - h*3/40, w, (int) (w * (144.0 / 1080)));
    game.batch.draw(about_button, (w / 2) - (w / 2), h / 2 + h/20 - 2*h*3/40, w, (int)(w*(144.0/1080)));

    game.batch.end();
}

My touchDown method.

public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    float pointerX = InputTransform.getCursorToModelX(windowWidth, screenX);
    float pointerY = InputTransform.getCursorToModelY(windowHeight, screenY);

    if(playButtonSprite.getBoundingRectangle().contains(pointerX, pointerY)) //Play button
    {
        game.setScreen(new PlayScreen(game));
        dispose();
    }

    return true;
}

I wanted to make it so when I clicked the Play "button", which is just a Sprite, it would move to PlayScreen. I did this by checking if the rectangle where the Play sprite was clicked. However, even though this part works, whenever I click in that rectangle area in PlayScreen, it runs the code again - it starts the PlayScreen over. How can I fix this?

Edit: also, there might be a better name for this question, so feel free to suggest.

Upvotes: 0

Views: 1140

Answers (1)

Phil Anderson
Phil Anderson

Reputation: 3146

This is happenning because when you change screen, you still have the same input processor in place which is checking whether that rectangle of the screen is tapped. Whether the button is visible or not is irrelevant.

You can do one of these to fix it...

  • Make each screen have its own input processor specific to its needs - this is the preferred option
  • Have a single input processor that checks what the current screen is before handling actions

Alternatively, look into frameworks like scene2d.ui to handle this sort of stuff for you.

Upvotes: 3

Related Questions