6

我试图在鼠标单击时获取,而不是在按下鼠标时获取。我的意思是我在循环中使用代码,如果我检测到是否按下鼠标,代码将执行很多时间,但我只想在鼠标单击时执行一次代码。

这是我的代码:

if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)){

            //Some stuff
}
4

3 回答 3

11

您可以使用Gdx.input.justTouched(),在单击鼠标的第一帧中为真。或者,正如其他答案所述,您可以使用 InputProcessor(或 InputAdapter)并处理touchDown事件:

Gdx.input.setInputProcessor(new InputAdapter() {
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        if (button == Buttons.LEFT) {
            // do something
        }
    }
});
于 2013-07-15T01:07:02.737 回答
11

请参阅http://code.google.com/p/libgdx/wiki/InputEvent - 您需要通过扩展 InputProcessor 并将您的自定义输入处理器传递给 Gdx.input.setInputProcessor() 来处理输入事件而不是轮询。

编辑:

public class MyInputProcessor implements InputProcessor {
   @Override
   public boolean touchDown (int x, int y, int pointer, int button) {
      if (button == Input.Buttons.LEFT) {
          // Some stuff
          return true;     
      }
      return false;
   }
}

无论您想在哪里使用它:

MyInputProcessor inputProcessor = new MyInputProcessor();
Gdx.input.setInputProcessor(inputProcessor);

如果发现使用此模式更容易:

class AwesomeGameClass {
    public void init() {
        Gdx.input.setInputProcessor(new InputProcessor() {
            @Override
            public boolean TouchDown(int x, int y, int pointer, int button) {
                if (button == Input.Buttons.LEFT) {
                    onMouseDown();
                    return true;
                }
                return false
            }

            ... the other implementations for InputProcessor go here, if you're using Eclipse or Intellij they'll add them in automatically ...
        });
    }

    private void onMouseDown() {
    }
}
于 2013-07-14T22:55:21.420 回答
1

如果没有 InputProcessor,您可以在渲染循环中像这样轻松使用:

@Override
public void render(float delta) {
    if(Gdx.input.isButtonJustPressed(Input.Buttons.LEFT)){
        //TODO:
    }
}
于 2019-09-16T21:30:58.993 回答