Expand description
Keyboard utility functions; allow querying state of keyboard keys and modifiers.
Example:
use ggez::event::{self, EventHandler, KeyCode, KeyMods};
use ggez::{graphics, timer};
use ggez::input::keyboard;
use ggez::{Context, GameResult};
struct MainState {
position_x: f32,
}
impl EventHandler for MainState {
fn update(&mut self, ctx: &mut Context) -> GameResult {
// Increase or decrease `position_x` by 0.5, or by 5.0 if Shift is held.
if keyboard::is_key_pressed(ctx, KeyCode::Right) {
if keyboard::is_mod_active(ctx, KeyMods::SHIFT) {
self.position_x += 4.5;
}
self.position_x += 0.5;
} else if keyboard::is_key_pressed(ctx, KeyCode::Left) {
if keyboard::is_mod_active(ctx, KeyMods::SHIFT) {
self.position_x -= 4.5;
}
self.position_x -= 0.5;
}
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult {
graphics::clear(ctx, [0.1, 0.2, 0.3, 1.0].into());
// Create a circle at `position_x` and draw
let circle = graphics::Mesh::new_circle(
ctx,
graphics::DrawMode::fill(),
glam::vec2(self.position_x, 380.0),
100.0,
2.0,
graphics::Color::WHITE,
)?;
graphics::draw(ctx, &circle, graphics::DrawParam::default())?;
graphics::present(ctx)?;
timer::yield_now();
Ok(())
}
fn key_down_event(&mut self, ctx: &mut Context, key: KeyCode, mods: KeyMods, _: bool) {
match key {
// Quit if Shift+Ctrl+Q is pressed.
KeyCode::Q => {
if mods.contains(KeyMods::SHIFT) && mods.contains(KeyMods::CTRL) {
println!("Terminating!");
event::quit(ctx);
} else if mods.contains(KeyMods::SHIFT) || mods.contains(KeyMods::CTRL) {
println!("You need to hold both Shift and Control to quit.");
} else {
println!("Now you're not even trying!");
}
}
_ => (),
}
}
}
Structs
Bitflags describing the state of keyboard modifiers, such as
Control
or Shift
.Tracks held down keyboard keys, active keyboard modifiers,
and figures out if the system is sending repeat keystrokes.
Enums
A key code.
Symbolic name for a keyboard key.
Functions
Returns currently active keyboard modifiers.
Checks if a key is currently pressed down.
Checks if the last keystroke sent by the system is repeated,
like when a key is held down for a period of time.
Checks if keyboard modifier (or several) is active.
Returns a reference to the set of currently pressed keys.