【问题标题】:LibGDX player movementLibGDX 玩家移动
【发布时间】:2017-07-10 20:09:46
【问题描述】:

我正在开发一款 2D 太空射击游戏,玩家只能左右移动。我在屏幕的左侧和右侧渲染了一个按钮,并不断检查它是否被触摸。这样做的问题是您必须抬起按钮的手指才能按下屏幕另一侧的按钮。我希望飞船朝着屏幕最后触摸的部分移动(即使您实际上没有抬起第一次触摸按钮的手指)。

    public void keyListener(float delta){

    //right movement
    if(Gdx.input.isKeyPressed(Keys.RIGHT) || (Gdx.input.isTouched() && game.cam.getInputInGameWorld().x >= arrowMoveX - 40) && !isPlayerHit)
        x+=SPEED*Gdx.graphics.getDeltaTime();


    //left movement
     if(Gdx.input.isKeyPressed(Keys.LEFT) || (Gdx.input.isTouched() && game.cam.getInputInGameWorld().x < arrowMoveWhite.getWidth() + 40) && !isPlayerHit)
        x-=SPEED*Gdx.graphics.getDeltaTime();

我尝试在其中添加另一个 if 语句来检查第二个动作,但这种方式只能在一个方向上起作用。 你能帮帮我吗?

【问题讨论】:

  • 创建一个“lastTouchedDirection”整数或布尔标志。按下其中一个按钮时更新标志。更新位置时,检查此标志以确定它应该移动的方向。您可能需要提取运动语句的一些条件。
  • 这是我尝试的第一件事,但它不是那样工作的。它不断检查您正在按下哪个按钮,因此假设您将此标志设置为 1 如果触摸右侧按钮,则设置为 0 如果触摸左侧按钮。当您按住右键时,它会不断将标志设置为 1,因此,如果您按下左键,它会将其设置为 0,但同时右键的条件为真,因此标志再次设置为 1。一个糟糕的解释,我知道,但是...:D
  • 我认为我必须同时检查两个按钮是否都被按下(未触摸),我不知道该怎么做。
  • 如果右,否则如果左,否则如果右和左

标签: java android libgdx


【解决方案1】:

您需要了解的是,Android 会按照触摸屏幕的时间顺序为每个单独的触摸编制索引,该索引称为“指针”。例如,当你只用一根手指触摸屏幕时,触摸指针为0,第二个触摸指针为1。libGDX注册的最高指针为20。

对于您的特定情况,您只想读取当前正在读取触摸的最高指针上的输入,并让 int 读取最高触摸。您可以遍历指针,并将 int 设置为实际上是指最近按下的最高指针的任何触摸事件,如下所示:

int highestpointer = -1; // Setting to -1 because if the pointer is -1 at the end of the loop, then it would be clear that there was no touch 
for(int pointer = 0; pointer < 20; pointer++) {
     if(Gdx.input.isTouched(pointer)) { // First check if there is a touch in the first place
          int x = Gdx.input.getX(pointer); // Get x position of touch in screen coordinates (far left of screen will be 0)
          if(x < arrowMoveWhite.getWidth() + 40 || x >= arrowMoveX - 40) {
               highestpinter = pointer; 
          } // Note that if the touch is in neither button, the highestpointer will remain what ever it was previously
     }
} // At the end of the loop, the highest pointer int would be the most recent touch, or -1

// And to handle actual movement you need to pass the highest pointer into Gdx.input.getX()
if(!isPlayerHit) { // Minor improvement: only check this once
     if(Gdx.input.isKeyPressed(Keys.RIGHT) || (highestpointer > -1 && Gdx.input.getX(highestpointer) >= arrowMoveX - 40)) {
        x+=SPEED*Gdx.graphics.getDeltaTime();
     } else if(Gdx.input.isKeyPressed(Keys.LEFT) || (highestpointer > -1 && Gdx.input.getX(highestpointer) < arrowMoveWhite.getWidth() + 40)) {
          x-=SPEED*Gdx.graphics.getDeltaTime();
     }
}

请注意,您可能需要一个单独的相机来绘制您的按钮(或任何 hud 元素),因为您不必担心将屏幕坐标转换为世界坐标,因为 x 是同一个方向。

如果您需要任何更改,请告诉我它是如何工作的!

【讨论】:

  • 噢,非常感谢!你不知道我已经尝试解决这个问题多久了。对于此类问题,这是我得到的最有用和最详细的答案!干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-25
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多