Stage.addListener 在 libgdx 中不工作

Stage.addListener not working in libgdx

我只是想在 libgdx 中向舞台添加点击监听器,但我的代码无法正常工作;

stage.addListener(new InputListener() {

        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

            Gdx.app.log("CLICK", "LISTENER");
            parallaxBackground.reverse();
            return super.touchDown(event, x, y, pointer, button);
        }
    });

这是我的主游戏画面,它继承自调用的抽象画面,

Gdx.input.setInputProcessor(stage);

摘要里class我也叫,

stage.act(delta);

我最明确地也从 child class

呼叫 super.render()

这是什么原因造成的!

编辑

我不知道这是否重要,但我的舞台没有演员,但我只想简单地确认一次点击。

由于你的舞台没有添加任何演员,所以你的舞台没有实体,所以无法触摸。

您可以添加创建一个与屏幕大小相同并与屏幕对齐的演员来执行您正在尝试的操作。像这样(未经测试):

Actor screenActor = new Actor(){
    public void act (float delta) {
        super.act(delta);
        Viewport viewport = getStage().getViewport();
        width = viewport.getScreenWidth();
        height = viewport.getScreenHeight();
        x = viewport.getScreenX();
        y = viewport.getScreenY();
    }
};

stage.addActor(screenActor);

您可以先添加这个 actor,这样其他 actor 就可以首先拦截触摸,这就是后备。

我是这样解决这个问题的:

  • 在 Photoshop 中,我创建了一个 100x100px 的图像,只在其中放置了一个图层,并将该图层的不透明度设置为 1%,我还删除了背景(这使图像完全透明)并将其另存为 .png 以将其用作纹理。
  • 我创建了一个 Actor 并将其命名为 BgActor 并为其绘制了纹理。

Here is the png image that I created

这是我的 Actor 的样子:

BgActor class:

public class BgActor extends Actor {
    private float x, y, width, height;

    private Texture texture = new Texture(Gdx.files.internal("images/transparent-bg.png"));

    public BgActor(float x, float y, float width, float height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;

        setTouchable(Touchable.enabled);
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        setBounds(x, y, width, height);
        batch.draw(texture, x, y, width, height);
    }

    public void dispose() {
        texture.dispose();
    }
}

实现(我用了你的Listener):

BgActor bgActor = new BgActor(0, 0, stage.getWidth(), stage.getHeight);
bgActor.addListener(new InputListener() {

        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

            Gdx.app.log("CLICK", "LISTENER");
            parallaxBackground.reverse();
            return super.touchDown(event, x, y, pointer, button);
        }
    });

......
stage.addActor(bgActor);

并且不要忘记在 Screenhide() 方法中处理 bgActor

祝你好运..