【问题标题】:Libgdx Hud Stage Button not Listening eventsLibgdx Hud 舞台按钮不监听事件
【发布时间】:2016-01-07 06:37:33
【问题描述】:

我正在尝试在当前阶段之上实现 HUD 阶段。我能够渲染和绘制 HUD 舞台,但其按钮的触摸事件没有响应。

我从 GameScreen 的 draw() 方法调用我的 drawHUD()。 drawHUD() 的代码是

public void drawHud(int scoreVal){
    Hud.this.getCamera().update();
    Hud.this.hudSpriteBatch.setProjectionMatrix(Hud.this.getCamera().combined);
    hudSpriteBatch.begin();
    scoreStr = "Score: " + scoreVal;
    glyphLayout.setText(scoreFont, scoreStr);
    halfWidth = glyphLayout.width/2;
    halfHeight = glyphLayout.height/2;
    scoreFont.draw(hudSpriteBatch, scoreStr, EatGame.CAMERA_WIDTH/2 - halfWidth, EatGame.CAMERA_HEIGHT - halfHeight);
    hudSpriteBatch.end();       
}

我在创建 HUD 时像这样向我的 pauseBtn 添加了一个监听器

pauseBtn.addListener(new InputListener() {
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("PauseBtn Touched");
            return false;
        }
}

我也通过设置按钮的边界进行了测试,但它没有响应事件。 感谢您的阅读和帮助。

【问题讨论】:

  • touchDown 必须返回一个布尔值。这可以编译吗?
  • 现在已编辑,我正在尝试删除一些代码。

标签: libgdx touch imagebutton hud


【解决方案1】:

通常你使用scene2d API 来实现按钮和类似的东西。 Stage 类负责处理正确参与者上的事件。看看 Stage#touchDown() 他们是如何做到的。如果您想自己实现它,则必须实现一个全局触摸监听器并检查坐标是否在按钮的边界内,然后使用正确的Event 对象在按钮上调用fire

我强烈推荐使用 scene2d api,它比编写自己的 hit-detection-firing-event-system 要容易得多。

【讨论】:

  • 我正在使用 ImageButton,它间接使用 Actor 作为其父级。所以基本上我已经在使用scene2d了。此外,我尝试使用 Actor 类,但没有成功。可能是我错过了什么。
  • 你必须使用Stage 类,否则它将不起作用。也许这个教程对你更有用:gamefromscratch.com/post/2013/11/27/… 在我的应用程序中,我尝试自己实现这个按钮的东西,但后来我回到了 scene2d,因为它更容易,我只能建议花一些时间使用这个框架。
  • 我的 Hud 类正在扩展“Stage”类。
  • 为什么要绘制按钮本身?你可以在舞台上调用draw...?不要忘记行动。像这样:stage.act(Gdx.graphics.getDeltaTime()); stage.draw();
  • 谢谢 morpheus05,搞定了。我已经尝试过 Gdx.input.setInputProcessor(Hud.ths) 但现在触摸事件在我的 GameScreen 上不起作用。我可以在 HUD 舞台或 GameScreen(屏幕和舞台)上设置 InputProcessor。我该如何处理?
【解决方案2】:

我必须使用 InputMultiplexer 从两个阶段获取输入事件。我就是这样做的。

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

这样它将接收来自两个阶段的事件。 GameScreen 和 Hud 是 Stage。

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多