Query key states
Querying key states is done using cer::isKeyDown()
and cer::isKeyUp()
.
// Gets a value indicating whether a specific key is currently pressed.
auto isKeyDown(Key key) -> bool;
// Gets a value indicating whether a specific key is currently released.
auto isKeyUp(Key key) -> bool;
Example
auto time = game.time();
auto dt = float(time.elapsed);
auto movement = dt * 200.0f;
if (isKeyDown(Key::Up)) {
spritePosition.y -= movement;
}
if (isKeyDown(Key::Down)) {
spritePosition.y += movement;
}
cerlib provides further convenience functions that allow you to detect changes in a key’s state.
auto wasKeyJustPressed(Key key) -> bool;
auto wasKeyJustReleased(Key key) -> bool;
wasKeyJustPressed
is true when a key was released in the previous frame, but is pressed in the current frame. wasKeyReleased
is the opposite, meaning that it detects when a key was released in the current frame.
Example
if (wasKeyJustPressed(Key::Space)) {
shoot();
}
Keyboard events
Note
This assumes that you’ve read Events.
The following events are related to the keyboard:
KeyPressEvent
: Raised when a key was pressed.KeyReleaseEvent
: Raised when a key was released.
Example
// ...
while (game.tick()) {
game.handleAllEvents(
[](KeyPressEvent e) {
logInfo("Key {} was pressed, with modifiers {}.",
e.key, e.modifiers);
},
[](KeyReleaseEvent e) {
logInfo("Key {} was released, with modifiers {}.",
e.key, e.modifiers);
},
cerIgnoreEvent,
);
// ...
}