Resets the internal state of this class to what it is during creation (nothing pressed, released or held down)
Handles a keyboard event updating the internal status. This will be called automatically if you register the listeners
via registerListeners
. If you have listeners being registered somewhere else entirely and would like to keep it
that way, you can manually call this method passing the KeyboardEvent.
Registers the keydown
and keyup
listeners on the passed element so that the class
can handle the input.
To avoid issues with focus it's best to pass document
here
Updates the internal state, should be called at the end of each frame.
Generated using TypeDoc
Handles the keyboard events and provides an API for interacting with it easily. The simplest way to use it is:
KeyboardInput
.registerListeners()
passing thedocument
.update
at the end of every update frame of your game.How does it work?
You need to call the
update()
method at the end of every frame to properly transition internal state. The workflow for this class is as follows:KeyboardInput
receives those events and updates its internal state.update()
is called on this class. (or at any point past when you know you'll interact with this class)Understanding key states
There are three states recognized by this class for a key: down, pressed and released:
pressed
if you want to know if a key was pressed at least once this frame.released
if you want to knof iw a key was releast at least once this frame.down
if you want to know if a key was either pressed this frame or pressed in any previous frame and not released so far.You may notice that in a situation where during the course of a single frame a key is both pressed and released, all three states will report true. That's an intentional design decision to avoid a very uncommon but still possible bug. Imagine this code:
if (keyboardInput.isKeyDown("a")) { this.move({x: -1}); }
If for some reason your game runs slow (maybe it naturally has low FPS or it's lagging at the moment), if you pressed and released the
a
key during the span of a single frame as a player you'd still expect the move to trigger - sure, you released the key but you also pressed it. The code can't useisKeyPressed
instead, because you want the player to keep moving as long as the key is down. You could work around this by expanding the condition toi.isKeyDown || i.isKeyPressed
, but the issues are: