Java 实现 InputProcessor 的 libgdx 多个对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23546544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:47:25  来源:igfitidea点击:

libgdx multiple objects implementing InputProcessor

javalibgdx

提问by TimSim

So on my ScreenI have two objects of the same class that implement InputProcessorwith the following keyDown()method:

所以在我的Screen我有InputProcessor使用以下keyDown()方法实现的同一个类的两个对象:

@Override
public boolean keyDown(int keycode) {
    if (keycode==fireKey) {
        System.out.println("Reporting keydown "+keyCode);
    }
    return false;
}

The problem is when I instantiate these two objects, only the last one instantiated receives any keyDownevents. I need both objects (or however many there are) to receive keyDownevents.

问题是当我实例化这两个对象时,只有最后一个实例化的对象接收任何keyDown事件。我需要两个对象(或无论有多少)来接收keyDown事件。

采纳答案by noone

You need to use an InputMultiplexerto forward the events to both InputProcessors. It will look like this:

您需要使用 anInputMultiplexer将事件转发到 both InputProcessors。它看起来像这样:

InputProcessor inputProcessorOne = new CustomInputProcessorOne();
InputProcessor inputProcessorTwo = new CustomInputProcessorTwo();
InputMultiplexer inputMultiplexer = new InputMultiplexer();
inputMultiplexer.addProcessor(inputProcessorOne);
inputMultiplexer.addProcessor(inputProcessorTwo);
Gdx.input.setInputProcessor(inputMultiplexer);

The multiplexer works like some kind of switch/hub. It receives the events from LibGDX and then deletegates them to both processors. In case the first processor returns truein his implementation, it means that the event was completely handled and it won't be forwarded to the second processor anymore. So in case you always want both processors to receive the events, you need to return false.

多路复用器的工作方式类似于某种交换机/集线器。它从 LibGDX 接收事件,然后将它们删除到两个处理器。如果第一个处理器true在他的实现中返回,则意味着该事件已被完全处理并且不会再转发到第二个处理器。因此,如果您总是希望两个处理器都接收事件,则需要返回false.

回答by Julien

Here is a code sample on LibGDX.info showing how to implement multiplexing with LibGDX:

这是 LibGDX.info 上的代码示例,展示了如何使用 LibGDX 实现多路复用:

https://libgdx.info/multiplexing/

https://libgdx.info/多路复用/

I hope it helps

我希望它有帮助