如何在 Libgdx 中向舞台发送触摸输入?

How to send a touch input to stage in 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

currentStage 实例已创建并设置为 InputProcessor。我在 400,200 上放置了一个按钮来捕获事件,但上面的代码未能这样做。

您可以使用 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);

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

当发生实际屏幕触摸时,Stage 确定触摸了哪个 actor 并直接在该 actor 上触发 InputEvent。如果您在根上触发 manually-created InputEvent,则只有根有机会响应它。

如果您想手动创建一个输入事件并让舞台确定将它提供给哪个演员,您可以调用 stage.hit() 如果它 returns 是一个演员,那就是可触摸的演员那是在触摸点下方,您可以在该 Actor 上触发事件。