Slick2D's Input
class has a isKeyPressed()
method that returns a boolean value according to whether the specified key has been pressed. I want to check if a key has been released in the same fashion.
I looked into adding a KeyListener
to the input object, and overriding the keyReleased()
method. However, because I am currently handling input in the update()
method of my BasicGame
, this would fracture my code by handling input in two different places, which I'd like to avoid.
Answer
So you've got callbacks, but you really want state.
Here's an adapter:
Every frame (or on callbacks), update an associative map (HashMap
in Java lingo) that maps from key codes to a status of whether that key was just pressed, is held down or was just released.
// In a `GameState` class
game.onTick()
// Turn "released" keys off and "pressed" keys "held"
for k,status of keys
if status is "pressed" then keys[k] = "held"
if status is "released" then keys[k] = null
// otherwise stay the same
game.onKeyPressed(k)
keys[k] = "pressed"
game.onKeyReleased(k)
keys[k] = "released"
Then interrogate that map from everywhere else that cares.
In Java, it'll likely be faster and more readable by refactoring all the state String
s to Enum
s, but this is is the idea. Of course, implementing getKeyReleased
is then a HashMap
-access one-liner.
No comments:
Post a Comment