【问题标题】:Screen responds when button is clicked单击按钮时屏幕响应
【发布时间】:2018-09-19 19:10:07
【问题描述】:

基本上,我有一个屏幕,其中有一个字符和一个按钮。触摸屏幕时字符跳动(使用 Gdx.input.justTouched 实现)。单击按钮时会打开 PauseMenu(按钮是舞台的演员,单击是使用 button.addListener(new ChangeListener() {....} 实现的)。我的 InputProcessor 设置在舞台上

Gdx.input.setInputProcessor(stage);

问题是当按钮被点击时,我的角色会跳跃(但他不应该)并且暂停菜单会打开。我正在通过 InputMultiplexer 进行搜索,但这不起作用(或者我可能以错误的方式使用它)。

感谢您的建议!

【问题讨论】:

  • 我认为您需要使用比justTouched 更多信息的事件,当您处理该事件时,您可以检查它是否在按钮区域并忽略它。

标签: java libgdx


【解决方案1】:

您可以使用InputMultiplexer

首先InputMultiplexer 是如何工作的。
InputMultiplexer 中,您可以执行许多InputProcessors 并且InputProcessor 具有返回布尔值的方法。
此布尔值表示事件是否已处理。
因此,如果方法返回 false,InputMultiplexer 会将事件交给下一个 InputProcessor
如果该方法返回 true,则该事件已被处理,并且该事件不会转到下一个 InputProcessor

现在我们为我们的屏幕创建一个InputProcessor,在这种情况下为TestScreenInput

public class TestScreenInput implements InputProcessor {

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        System.out.println("Touch down");
        character.jump();
        return true;
    }

    @Override
    ... //all other methods from InputProcessor
}

touchDown 方法返回 true,因此下一个 InputProcessor 不会收到 touchDown 事件

在我们的屏幕类 (TestScreen) 中,我们创建了 Stage

public class TestScreen implements Screen {
    private Stage stage;

    @Override
    public void show() {
        stage = new Stage();
    }
}

现在我们将使用ChangeListener 创建我们的TextButton
问题是,我们怎么能说事件被处理了?
ChangeListener::changed(ChangeEvent event, Actor actor) 不返回布尔值。

当我们查看Stage 类时,我们可以找到touchDown 方法并且该方法返回:

boolean handled = event.isHandled();
return handled;

eventEventChangeEvent 扩展 Event 的类型
在我们的changed(ChangeEvent event, Actor actor) 方法中,我们有一个ChangeEvent。所以我们要做的就是设置这个事件被处理。
Event中有一个方法:

public void handle () { handled = true;}

现在我们知道如何创建我们的 Button:

TextButton button = new TextButton("Click", skin);
button.addListener(new ChangeListener() {
    @Override
    public void changed(ChangeEvent event, Actor actor) {
        System.out.println("Click Button");
        event.handle(); //set the event handled = true
    }
});

stage.addActor(button);

最后,我们创建了InputMultiplexer。重要的是该阶段出现在我们的TestScreenInput 之前,因为TestScreenInput 会将touchDown 标记为已处理,而stage 永远不会收到它们。

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

【讨论】:

  • 是的,这行得通,你的解释很清楚,谢谢!
  • @Morchul "become" 在特定上下文中听起来像是德国的假朋友。可能您的意思是“接收”; ]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-21
  • 2021-02-26
  • 2012-05-06
相关资源
最近更新 更多