keyboard_input/
keyboard_input.rs

1//! Demonstrates handling a key press/release.
2
3use bevy::{input::keyboard::Key, prelude::*};
4
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .add_systems(Update, keyboard_input_system)
9        .run();
10}
11
12/// This system responds to certain key presses
13fn keyboard_input_system(
14    keyboard_input: Res<ButtonInput<KeyCode>>,
15    key_input: Res<ButtonInput<Key>>,
16) {
17    // KeyCode is used when you want the key location across different keyboard layouts
18    // See https://w3c.github.io/uievents-code/#code-value-tables for the locations
19    if keyboard_input.pressed(KeyCode::KeyA) {
20        info!("'A' currently pressed");
21    }
22
23    if keyboard_input.just_pressed(KeyCode::KeyA) {
24        info!("'A' just pressed");
25    }
26    if keyboard_input.just_released(KeyCode::KeyA) {
27        info!("'A' just released");
28    }
29
30    // Key is used when you want a specific key, no matter where it is located.
31    // This is useful for symbols that have a specific connotation, e.g. '?' for
32    // a help menu or '+'/'-' for zoom
33    let key = Key::Character("?".into());
34    if key_input.pressed(key.clone()) {
35        info!("'?' currently pressed");
36    }
37    if key_input.just_pressed(key.clone()) {
38        info!("'?' just pressed");
39    }
40    if key_input.just_released(key) {
41        info!("'?' just released");
42    }
43}