How leafwing-input-manager works
mainThe leafwing-input-manager is an input-action manager for Bevy that decouples raw hardware inputs (keyboard, mouse, gamepad) from logical game actions.
Core Workflow
- Define Actions: Create an enum representing your game's logical actions (e.g.,
Jump,Move) and derive theActionliketrait. - Map Inputs: Use an
InputMap<A>component on an entity to define which hardware inputs (likeKeyCode::SpaceorGamepadButton::South) trigger which actions. - Collect State: The plugin automatically populates an
ActionState<A>component on the same entity, which aggregates all input sources into a single, easy-to-query state. - Consume Actions: In your game systems, query for
&ActionState<A>to check for button presses, releases, or axis values.
Key Abstractions
Actionlike: A trait derived by your action enum to allow it to be used within the manager.InputMap<A>: A component that stores the many-to-many mappings between inputs and actions. It supports chords (combinations of keys) and multiple input types for the same action.ActionState<A>: A component that holds the current state of all actions for an entity, providing methods like.just_pressed(),.pressed(), and axis-related queries.
// 1. Define actions
#[derive(Actionlike, PartialEq, Eq, Hash, Clone, Copy, Debug, Reflect)]
enum Action {
Run,
Jump,
}
// 2. Map inputs on an entity
let input_map = InputMap::new([(Action::Jump, KeyCode::Space)]);
commands.spawn(input_map).insert(Player);
// 3. Read state in a system
fn jump(query: Query<&ActionState<Action>, With<Player>>) {
let action_state = query.single();
if action_state.just_pressed(&Action::Jump) {
println!("I'm jumping!");
}
}