libgdx的touchDown方法只被调用一次

4
我是LibGdx的新手,遇到了输入处理问题。
每当触摸按下时,我的玩家需要发射子弹。 但似乎这个方法只被调用一次...
然后用户必须再次点击才能发射另一颗子弹。
我想在点击时始终发射子弹...
有没有办法处理这种情况?

哪种具体的方法?(在Libgdx中有多种获取触摸事件的方式。) - P.T.
InputProcessor中的touchDown方法。当我点击时...它只被调用一次...不管我是按住点击还是快速释放。我需要检测用户何时按住点击。有touchDragged方法...但只有当我按住点击并移动光标时才会被调用...这样我就无法检测用户何时仅按住点击并将光标保持在同一位置...希望您能理解这个想法...这非常简单,我无法相信没有方法来实现这一点。 - Veljko
3个回答

6

请看一下 "轮询" 触触摸输入,而不是获取 输入事件。因此,在您的渲染或更新方法中,使用以下代码:

 boolean activeTouch = false;

 if (Gdx.input.isTouched(0)) {
    if (activeTouch) {
       // continuing a touch ...
    } else {
       // starting a new touch ..
       activeTouch = true;
    }     
 } else {
    activeTouch = false;
 }

好的,那很有道理...但我需要获取触摸的X和Y坐标,这样我才能进行旋转和角度的一些计算。如何使用这种方法获取X和Y坐标? - Veljko
点击“轮询触摸输入”链接,您将看到您还可以读取当前的触摸坐标(Gdx.input.getX(0)等)。按钮和按键也是类似的... - P.T.

2

我使用了连续输入处理

这是通过为您的演员设置标志来完成的,例如:

public class Player{
  private boolean firing = false;
  private final Texture texture = new Texture(Gdx.files.internal("data/player.png"));

  public void updateFiring(){
    if (firing){
        // Firing code here
        Gdx.app.log(TAG, "Firing bullets");
    }
  }

  public void setFiring(boolean f){
    this.firing  = f;
  }

  Texture getTexture(){
    return this.texture;
  }

}

现在我正在我的Application类中实现InputProcessor。
@Override
public void create() {
    player= new Player();
    batch = new SpriteBatch();
    sprite = new Sprite(player.getTexture());
    Gdx.input.setInputProcessor(this);
}
@Override
public void render() {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.begin();
    sprite.draw(batch);
    // Update the firing state of the player
    enemyJet.updateFiring();
    batch.end();
}

@Override
public boolean keyDown(int keycode) {
    switch (keycode){
        case Input.Keys.SPACE:
            Gdx.app.log(TAG, "Start firing");
            player.setFiring(true);

    }
    return true;
}

@Override
public boolean keyUp(int keycode) {
    switch (keycode){
        case Input.Keys.SPACE:
            Gdx.app.log(TAG, "Stop firing");
            player.setFiring(false);

    }
    return true;
}

完成


2

我已经成功解决了这个问题,没有使用连接池的概念。

我有自定义的InputProccesor,其中使用了与P.T.提到的类似的逻辑。 在touchDown时,我启动一个线程来发射子弹并进行一些计算,因为我需要访问Renderer类中的一些方法,所以我必须使用。

   Gdx.app.postRunnable(new Runnable() {
        @Override
        public void run() {
        // process the result, e.g. add it to an Array<Result> field of the ApplicationListener.
        shootBullet(screenX, screenY);
        }
    });

为避免OpenGL上下文异常。
在touchUp方法中取消拍摄线程。
谢谢您的建议!

不错!拥有两个有用的解决方案真是太好了。 :) - P.T.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接