如何将触摸输入发送到 Libgdx 中的舞台



我正在尝试映射键盘的键以触摸舞台上的某个点。这是我当前的代码,但它不会崩溃或做任何事情。

InputEvent touch = new InputEvent();
touch.setType(InputEvent.Type.touchUp);
touch.setStageX(400);
touch.setStageY(200);
currentStage.getRoot().fire(touch); //this doesn't do anything

创建当前阶段实例并将其设置为输入处理器。我在 400,200 上放置了一个按钮来捕获事件,但上面的代码未能这样做。

似乎期望 InputEvent 导致将层次结构中的每个参与者与坐标进行比较,以确定它是否响应。这不是 Stage 处理输入事件的方式。

当实际屏幕触摸发生时,Stage 会确定触摸了哪个角色,并直接在该角色上触发 InputEvent。如果在根上触发手动创建的 InputEvent,则只有根才有机会响应它。

如果要手动创建输入事件并让舞台确定要将其提供给哪个Actor,则可以调用stage.hit(),如果它返回Actor,则为触摸点下的可触摸Actor,您可以在该Actor上触发事件。

您可以使用下一个Stage方法来模拟用户参与度:

/** 
 * Applies a touch down event to the stage and returns true if an actor 
 * in the scene {@link Event#handle() handled} the event. 
 */
public boolean touchDown(int screenX, int screenY, int pointer, int button)
/** 
 * Applies a touch moved event to the stage and returns true if an actor
 * in the scene {@link Event#handle() handled} the
 * event. Only {@link InputListener listeners} that returned true for 
 * touchDown will receive this event. 
 */
public boolean touchDragged (int screenX, int screenY, int pointer) 
/** 
 * Applies a touch up event to the stage and returns true if an actor 
 * in the scene {@link Event#handle() handled} the event.
 * Only {@link InputListener listeners} that returned true for 
 * touchDown will receive this event. 
 */
public boolean touchUp (int screenX, int screenY, int pointer, int button)

在您的情况下:

 Vector2 point = new Vector2(400, 300);
 currentStage.stageToScreenCoordinates(point);
 // this method works with screen coordinates
 currentStage.touchDown((int)point.x, (int)point.y, 0, 0);

最新更新