libGDX Stage input handling

4.2k views Asked by At

I have an Stage class that handles touch input.

In the Screen class I set the stage as InputProcessor:

stageTest = new StageTest(new ScreenViewport());
Gdx.input.setInputProcessor(stageHUD);

But now I want to add a force to an Box2d object always a gesture input happens.

public class ActSwipe extends Actor {

    private int tmpPointer;
    private float
            tmpX,
            tmpY,
            deltaX,
            deltaY,
            rad;
    protected float
            forceX,
            forceY;


    public ActSwipe() {
        this.setName("SwipeAction");
        this.setTouchable(Touchable.enabled);
        this.addListener(new InputListener() {
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                if(tmpPointer == 0) {
                    tmpPointer = pointer;
                    tmpX = x;
                    tmpY = y;
                }
                return true;
            }

            @Override
            public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
                if (tmpPointer == pointer) {
                    tmpPointer = 0;
                    deltaX = x - tmpX;
                    deltaY = y - tmpY;
                    rad = (float) Math.atan2(deltaY, deltaX);
                    forceX = (float) Math.cos(rad);
                    forceY = (float) Math.sin(rad);
                }
            }
        });
    }

}
1

There are 1 answers

0
Chanandler Bong On

You can implement InputProcessor (or extend InputAdapter) in your screen and override its methods with your code.

Then use InputMultiplexer like this:

InputMultiplexer multiplexer = new InputMultiplexer();
Gdx.input.setInputProcessor(multiplexer);
multiplexer.addProcessor(this);
multiplexer.addProcessor(stage)

In the overridden methods you need to make sure that an object that was hit is an object that should be handled by your input processor and not the one from the scene. If so, return true from the method, so the event won't be passed to the latter.