事件處理可以更加準确的擷取使用者的輸入。事件處理提供了一種可以通過使用者接口進行互動的方法。比如按下、釋放一個按鈕。
事件處理通過觀察者模式來完成。首先,需要實作InputProcessor接口:
public class MyInputProcessor implements InputProcessor { @Override public boolean keyDown (int keycode) { return false; } public boolean keyUp (int keycode) { public boolean keyTyped (char character) { public boolean touchDown (int x, int y, int pointer, int button) { public boolean touchUp (int x, int y, int pointer, int button) { public boolean touchDragged (int x, int y, int pointer) { public boolean mouseMoved (int x, int y) { public boolean scrolled (int amount) {
前三個方法允許你監聽鍵盤事件:
keyUp():當一個按鍵釋放時觸發。傳回key code。
keyTyped():當一個Unicode字元通過鍵盤輸入獲得時生成。
接下來的三個方法報告滑鼠或觸摸事件:
touchDown():當手指按到螢幕上時或滑鼠按下時觸發該事件。報告坐标、指針索引和滑鼠按鍵(觸摸操作預設左鍵)。
touchUp():當手機從螢幕釋放或者滑鼠釋放時調用。報告最後的坐标、指針索引和滑鼠按鍵(觸摸預設左鍵)。
touchDragged():當手指在螢幕上拖動或滑鼠在螢幕上拖動時觸發該事件。傳回坐标和指針索引。滑鼠按鍵将不會傳回。
mouseMoved():當滑鼠在螢幕上移動并沒有按鍵按下時觸發。這個方法僅僅适用于桌面環境。
scrolled():滑鼠滑輪滾動時觸發。傳回1或-1。不能在觸摸屏中觸發。
每個方法傳回一個布爾類型。我将在之後解釋原因。
一旦你自己實作InputProcessor接口,你必須告訴Libgdx:
MyInputProcessor inputProcessor = new MyInputProcessor(); Gdx.input.setInputProcessor(inputProcessor);
這樣的話,所有的輸入事件都會放到MyInputProcessor執行個體中。在ApplicationListener.render()之前調用。
InputAdapter實作了InputProcessor接口,并在每個方法中傳回false。你可以對InputAdapter進行擴充。這樣,你就可以實作你需要的方法。你同樣可以使用一個匿名類。
Gdx.input.setInputProcessor(new InputAdapter () {
// 你的代碼
return true;
});
有時,你需要控制InputProcessor。比如應用UI線程優先,輸入事件處理次之。你可以通過InputMultiplexer類來實作:
InputMultiplexer multiplexer = new InputMultiplexer(); multiplexer.addProcessor(new MyUiInputProcessor()); multiplexer.addProcessor(new MyGameInputProcessor()); Gdx.input.setInputProcessor(multiplexer);
InputMultiplexer将會處理第一個添加的InputProcessor的所有的新的事件。如果這個InputProcessor傳回false。将會處理下一個InputProcessor。
如果你向通過Input Processor移動一個actor,你需要注意的是之後在按下後才會處理,要想持續處理輸入,或者移動精靈,你可以添加一個flag到你的actor中。
public class Bob { boolean leftMove; boolean rightMove; ... updateMotion() if (leftMove) x -= 5 * Gdx.graphics.getDeltaTime(); if (rightMove) x += 5 * Gdx.graphics.getDeltaTime(); public void setLeftMove(boolean t) if(rightMove && t) rightMove = false; leftMove = t; public void setRightMove(boolean t) if(leftMove && t) leftMove = false; rightMove = t;
接下來,如下處理:
public boolean keyDown(int keycode) switch (keycode) case Keys.LEFT: bob.setLeftMove(true); break; case Keys.RIGHT: bob.setRightMove(true); public boolean keyUp(int keycode) bob.setLeftMove(false); bob.setRightMove(false);