检查哪个演员被按下了? (libgdx / android studio)

时间:2015-02-15 04:35:46

标签: android button libgdx actor stage

我对android编程和libgdx / scene2d都很新,还有很多好东西。我在屏幕上有四个方向键,当他们被按下时,他们正在四处乱晃地移动一个“老兄”。我想知道是否有人知道有一种方法来拥有一个InputListener,并且在该侦听器内部有一种方法来检查在舞台上按下哪个actor,并根据它做一些事情,而不是有四个不同的inputlisteners和touchup / down方法,每个文本按钮一个,我只想要一个。这就是我所拥有的,需要在这个方法中检查哪个actor被按下了。感谢阅读和帮助:D

InputListener inlis = new InputListener(){//Creating an InputListener to assign to each button instead of writing the same code four times :D
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Press");
            return true;
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Release");
        }
    };
    tbRight.addListener(inlis);
    tbLeft.addListener(inlis);
    tbDown.addListener(inlis);
    tbUp.addListener(inlis);

1 个答案:

答案 0 :(得分:1)

一次编写每段代码都是一种很好的愿望。你可以写一次,然后四次(或更多次)使用它。

1)使用InputListener方法创建基类:

public class Button extends Actor {
    int key;

    ... // All other Actor methods goes here

    public void addListeners() {
        mouseListener = new InputListener() {
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                doAction();
                return true;
            }
        };
        addListener(mouseListener);

        keyboardListener = new InputListener() {
            @Override
            public boolean keyDown(InputEvent event, int keyCode) {
                if (event.getKeyCode() == key) {
                    doAction();
                    return true;
                } else {
                    return false;
                }
            }
        };
        getStage().addListener(keyboardListener);

    protected void doAction() {
        // This method is empty. We will override it later.
        // You can declare it abstract if you want.
    }
}

2)然后使用每个按钮的所需功能扩展它,如下所示:

public class DownButton extends Button {
    public DownButton(float x, float y, int buttonSize) {
        super(x, y, buttonSize);
        key = Input.Keys.DOWN;
    }

    @Override
    protected void doAction() {
        System.out.println("Go down");
    }
}

3)最后,您可以将此Actor添加到您的舞台:

    ...
    DownButton downButton = new DownButton(100, 100, buttonSize);
    stage.addActor(downButton);
    downButton.addListeners();
    ...

在这种情况下,您只需编写一行代码即可为每个新按钮添加侦听器。