Search code examples
javaandroidlibgdxtouchscreen

LibGDX: Implement touch screen, without touching the screen


I'm using LibGDX.

Let's say that I wan't to jump - but not really touching the screen, I don't want to use a keyboard forsay, And implement the touch, like i was touching the screen. Can i do that?

Can one let's say "test" the button without pressing it (from the touch screen of application / android / ios / etc..)?

Example of a button from InputListener:

final Image imageJumpButton = new Image(new Texture("jbjump.png"));
imageJumpButton.addListener(new InputListener() {

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        JOYSTICK_UP= true;
        return true;
    }


    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        JOYSTICK_UP = false;
    }
});

I thank you.


Solution

  • I would suggest to use Button class for a button instead of Image. There is a convenient way to do what you ask with Button:

    final Button imageJumpButton = new Button(new TextureRegionDrawable(new TextureRegion(new Texture("jbjump.png"))));
    //use ChangeListener instead of InputListener
    imageJumpButton.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                Gdx.app.log("", "Button is pressed");
            }
        });
    

    Then you could programmatically press the button:

    //this will trigger changed() method of the ChangeListener
    imageJumpButton.toggle();
    

    Update

    If you want to do something, while the button is pressed, call this in your render() method:

    if (button.isPressed())
        //do something each frame, while button is pressed
    

    For example, if you want a player to run, while the button is pressed, it would be something like this:

    public void update(float deltaTime) {
        if (button.isPressed())
            player.x += deltaTime * velocityX;
    }
    

    And by the way, you don't need to add ChangeListener to the button in this case.