Input & Events
Handle keyboard, mouse, gamepad, and in-game events in Bevy - responsive controls without tangled systems.
Busca en todas las páginas de la documentación
Handle keyboard, mouse, gamepad, and in-game events in Bevy - responsive controls without tangled systems.
fn jump(
keys: Res<ButtonInput<KeyCode>>,
mut q: Query<&mut PlayerState>,
) {
if keys.just_pressed(KeyCode::Space) {
for mut state in &mut q {
state.request_jump = true;
}
}
}When to reach for this:
use bevy::prelude::*;
#[derive(Event)]
struct PlayerShot {
entity: Entity,
}
#[derive(Component)]
struct Cooldown(Timer);
fn shooting(
mouse: Res<ButtonInput<MouseButton>>,
mut commands: Commands,
mut reader_q: Query<(Entity, &mut Cooldown)>,
mut events: EventWriter<PlayerShot>,
time: Res<Time>,
) {
if !mouse.just_pressed(MouseButton::Left) {
return;
}
for (entity, mut cd) in &mut reader_q {
cd.0.tick(time.delta());
if cd.0.finished() {
events.write(PlayerShot { entity });
cd.0.reset();
}
}
}
fn on_shot(mut events: EventReader<PlayerShot>) {
for e in events.read() {
println!("shot from {:?}", e.entity);
}
}What this demonstrates:
just_pressed edge for single fire per clickUpdate systems.leafwing-input-manager or custom) bind keys to intents.| Resource | Use |
|---|---|
ButtonInput<KeyCode> | Keyboard |
ButtonInput<MouseButton> | Mouse buttons |
Axis<GamepadAxis> | Sticks (via gamepad entities) |
pressed for actions needing once - auto-repeat feel wrong. Fix: just_pressed for discrete actions.time.delta_secs()..after(shooting) on reader.Gamepad connections on insert and map per device.| Alternative | Use When | Don't Use When |
|---|---|---|
| Polling only | Simple jam | Many rebindable actions |
| Channel from OS thread | Custom controllers | Bevy input sufficient |
| Networked input sync | Online multiplayer | Local single-player |
| UI-only buttons | Menu-heavy game | Fast twitch gameplay |
Store HashMap<Action, KeyCode> in resource; map in input system each frame.
AccumulatedMouseMotion resource (Bevy 0.14+) for FPS camera look.
Bevy mobile support evolving - map touch to virtual joystick components.
Interaction component on UI nodes; skip world input when Hovered on menu.
Record just_pressed edges with frame numbers; playback writes synthetic input resource.
State enum disables gameplay systems with run_if(in_state(Playing)).
Multiple EventReader instances each receive all events unless using reader ordering groups.
Higher-level action state machine over raw buttons - good for complex controls.
Input read in Update; physics response often in FixedUpdate - see Game Loops & Timing.
Game Dev Basics keyboard move example.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026