Here is my keyboardhandler class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| public class KeyboardHandler {
public List<Character> charsPressed = new ArrayList<Character>();
public KeyboardHandler() { }
private void processInput() {
while (Keyboard.next()) {
int key = Keyboard.getEventKey(); boolean state = Keyboard.getEventKeyState();
charsPressed.add(Keyboard.getEventCharacter());
toggle(key, state);
}
}
private void toggle(int keycode, boolean state) { for (Key key : keys) { if (key.keycode == keycode) key.toggle(state); } }
public void tick() {
processInput();
for (Key key : keys) { key.tick(); } } public void releaseAll() { for(int i=0;i<keys.size();i++) { keys.get(i).pressed = false; keys.get(i).down = false; } }
public List<Key> keys = new ArrayList<Key>(); public Key KEY_W = new Key(Keyboard.KEY_W); public Key KEY_A = new Key(Keyboard.KEY_A); public Key KEY_S = new Key(Keyboard.KEY_S); public Key KEY_D = new Key(Keyboard.KEY_D);
public Key KEY_CTRL = new Key(Keyboard.KEY_LCONTROL); public Key KEY_R = new Key(Keyboard.KEY_R); public Key KEY_T = new Key(Keyboard.KEY_T);
public Key KEY_K = new Key(Keyboard.KEY_K);
public Key KEY_V = new Key(Keyboard.KEY_V);
public class Key {
public int keycode;
public boolean down = false, pressed = false; private boolean wasDown = false;
public Key(int keycode) { this.keycode = keycode; keys.add(this); }
public void toggle(boolean bool) { down = bool; }
public void tick() {
if (!wasDown && down) { pressed = true; } else { pressed = false; }
wasDown = down; }
}
} |
You need to call KeyboardHandler.tick method every time you update your game. Key.down is a boolean which says if key is currently down. Key.pressed is a boolean which says if the key was pressed.