Highfield
Highfield

Reputation: 15

LibGDX game: Check if button is touched when touchDown is called

I am currently making a libGDX game for Android devices. I want to have a method which calls a function when touchDown is called but not when the button has been clicked. This is because I am setting a target for a turret and it should not rotate when the button is clicked.

The code I have at the moment is

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    if (state != STATE.GAMEOVERLOST && state != STATE.PAUSED
            && state != STATE.EXITMENU && !slowButton.isOver()
            && !pauseButton.isPressed())
        turret.setTargetAngle(screenX, screenY);
    return true;
}

This overrides the function in the InputProcessor class my class implements.

This code works:

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    if (state != STATE.GAMEOVERLOST && state != STATE.PAUSED
            && state != STATE.EXITMENU && !slowButton.isPressed()
            && !pauseButton.isPressed())
        turret.setTargetAngle(screenX, screenY);
    return true;
}

The fact that touchDragged works but touchDown does not indicates that the button does not get marked as 'pressed' until after the first instance.

I have also tried using Button.isOver() instead of Button.isPressed() but this still does not work as expected.

Anyone got any tips?

Upvotes: 1

Views: 2681

Answers (1)

kabb
kabb

Reputation: 2502

You can use the method hit(x, y, touchable) on the button. It finds the deepest actor at the provided coordinates. You should call it from the stage, and if it returns the pauseButton, then the pauseButton was clicked. If it returns something that isn't the slowButton, or null, then it wasn't clicked. More info on hit detection on the Libgdx wiki.

So you would do something like this:

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    if (state != STATE.GAMEOVERLOST && state != STATE.PAUSED
            && state != STATE.EXITMENU && !slowButton.isOver()
            && !stage.hit(screenX, screenY, true).equals(pauseButton))
        turret.setTargetAngle(screenX, screenY);
    return true;
}

However, you might have to convert the screen coordinates to stage coordinates, depending on your coordinate system setup.

Upvotes: 2

Related Questions