1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use bevy::prelude::*;
use leafwing_input_manager::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// This plugin maps inputs to an input-type agnostic action-state
// We need to provide it with an enum which stores the possible actions a player could take
.add_plugin(InputManagerPlugin::<Action>::default())
// The InputMap and ActionState components will be added to any entity with the Player component
.add_startup_system(spawn_player)
// Read the ActionState in your systems using queries!
.add_system(jump)
.run();
}
// This is the list of "things in the game I want to be able to do based on input"
#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Hash, Debug)]
enum Action {
Run,
Jump,
}
#[derive(Component)]
struct Player;
fn spawn_player(mut commands: Commands) {
commands
.spawn(InputManagerBundle::<Action> {
// Stores "which actions are currently pressed"
action_state: ActionState::default(),
// Describes how to convert from player inputs into those actions
input_map: InputMap::new([(KeyCode::Space, Action::Jump)]),
})
.insert(Player);
}
// Query for the `ActionState` component in your game logic systems!
fn jump(query: Query<&ActionState<Action>, With<Player>>) {
let action_state = query.single();
// Each action has a button-like state of its own that you can check
if action_state.just_pressed(Action::Jump) {
println!("I'm jumping!");
}
}