Search code examples
javaandroidlibgdx

how can I add Action to a texture packer in libgdx?


I'm trying to create eventListner on each image (playIcon,pauseIcon) but its not working using touchUp and touchDown

here is my code:

TextureAtlas buttonsPlayPause = new TextureAtlas("uiii/uiii.pack");
skin.addRegions(buttonsPlayPause);
TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
textButtonStyle.font = font;
textButtonStyle.up = skin.getDrawable("pauseIcon");
textButtonStyle.checked = skin.getDrawable("playIcon");
TextButton button = new TextButton("", textButtonStyle);
button.setY(pauseY);
button.setX(Gdx.graphics.getWidth()/6);
button.setSize(150,150);
stage.addActor(button);

//pause/playAction
button.addListener(new ClickListener() {
        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {resume();
              }
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
         pause();
            return true;
        }
    });

What happens now is that the button listener behaves as 'istouched()' rather than 'justtouched()'. When I click the button, the game is paused but whenever I remove my finger, there's no pause, the game runs.


Solution

  • If I understand correctly, you want this button to toggle between Play and Pause, calling either pause() or resume() based on current state.

    The Button class already has a built-in internal InputListener, so all you need is a ChangeListener to react to button presses:

    //pause/playAction
    button.addListener(new ChangeListener() {
        @Override
        public void changed (ChangeEvent event, Actor actor) {
            if (button.isChecked())
                resume();
            else
                play();
        }
    });
    

    Make sure you mark it final when you first declare it, so the listener can reference it:

    //...
    final TextButton button = new TextButton("", textButtonStyle);
    //...