Here is my keyboardhandler class.
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.