I'm making an inventory system for my pure Java game right now. Currently, the game runs at a 60UPS, and inputs are checked each update.
I have inputs set up using arrays of the current update and last update's key presses:
private final int NUM_KEYS = 256;
private boolean[] pressedKeys;
private boolean[] pressedKeysLast;
// yes, those are initialized in the actual code :)
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() <= NUM_KEYS) {
// Presses the key if it is valid.
pressedKeys[e.getKeyCode()] = true;
}
}
/**
* Handles the keyReleased event.
*/
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() <= NUM_KEYS) {
// Releases the key if it is valid.
pressedKeys[e.getKeyCode()] = false;
}
}
/**
* Updates the input class and updates the input arrays.
*/
public void update() {
/*
* Sets the values of last frame's pressed keys
* to this frame's pressed keys.
*/
for (int index = 0; index < NUM_KEYS; index++) {
pressedKeysLast[index] = pressedKeys[index];
}
}
/**
* Determines if a specific key has just been pressed.
* @param keyCode The key to be checked.
* @return True if the key is pressed, false if it is not.
*/
public boolean isKeyDown(int keyCode) {
/*
* This will return true if the key has been pressed in
* this frame, but not in the last frame.
*/
return pressedKeys[keyCode] && !pressedKeysLast[keyCode];
}
This works fine, but for logging quick keypresses, such quickly pressing and releasing "E" to open the player's inventory, this system is too fast.
I have seen that every time that I try to quickly press and release a key to see if I can open the inventory using isKeyDown(KeyEvent.VK_E)
, the update()
method is called approximately 3 times, and since the arrays reset each frame, I only have a 0.05 seccond window to achieve the result I want, which is to get when the key is pressed and released quickly.
I am looking for suggestions to my problem so theinput.isKeyDown(int keycode)
method be able to determine when keycodes are quickly pressed, regardless if the duration of the press is 0.05s or 1.5s.