generated from Leafwing-Studios/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 122
/
action_state_resource.rs
52 lines (46 loc) · 1.67 KB
/
action_state_resource.rs
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
46
47
48
49
50
51
52
//! Oftentimes your input actions can be handled globally and are
//! best represented as a [`Resource`].
//!
//! This example demonstrates how to create a simple `ActionLike`
//! and include it as a resource in a bevy app.
use bevy::prelude::*;
use leafwing_input_manager::{prelude::*, user_input::InputKind};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(InputManagerPlugin::<PlayerAction>::default())
// Initialize the ActionState resource
.init_resource::<ActionState<PlayerAction>>()
// Insert the InputMap resource
.insert_resource(PlayerAction::mkb_input_map())
.add_systems(Update, move_player)
.run();
}
#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Hash, Debug, Reflect)]
pub enum PlayerAction {
Move,
Jump,
}
// Exhaustively match `PlayerAction` and define the default binding to the input
impl PlayerAction {
fn mkb_input_map() -> InputMap<PlayerAction> {
use KeyCode::*;
InputMap::new([
(UserInput::Single(InputKind::Keyboard(Space)), Self::Jump),
(UserInput::VirtualDPad(VirtualDPad::wasd()), Self::Move),
])
}
}
fn move_player(
// action_state is stored as a resource
action_state: Res<ActionState<PlayerAction>>,
) {
if action_state.pressed(PlayerAction::Move) {
// We're working with gamepads, so we want to defensively ensure that we're using the clamped values
let axis_pair = action_state.clamped_axis_pair(PlayerAction::Move).unwrap();
println!("Move: ({}, {})", axis_pair.x(), axis_pair.y());
}
if action_state.pressed(PlayerAction::Jump) {
println!("Jumping!");
}
}