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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use std::collections::HashMap;
use amethyst::input::InputHandler;
#[derive(Clone, Copy, PartialEq)]
enum ActionState {
Down,
Up,
Pressed,
None,
}
impl Default for ActionState {
fn default() -> Self {
ActionState::None
}
}
/// Manages input actions.
/// Stores data about which actions are _down_, _up_, or being _pressed_.
pub struct InputManager {
actions: HashMap<String, ActionState>,
}
impl InputManager {
/// Creates a new `InputManager`.
pub fn new() -> Self {
Self::default()
}
/// Returns `true` if the action with the given name was pressed _down_.
pub fn is_down<T>(&self, action: T) -> bool
where
T: ToString,
{
self.is_action_in_state(action, ActionState::Down)
}
/// Returns `true` if the action with the given name was released (_down_).
pub fn is_up<T>(&self, action: T) -> bool
where
T: ToString,
{
self.is_action_in_state(action, ActionState::Up)
}
/// Returns `true` if the action with the given name is being _pressed_ down.
pub fn is_pressed<T>(&self, action: T) -> bool
where
T: ToString,
{
self.is_action_in_state(action, ActionState::Pressed)
}
fn is_action_in_state<T>(&self, action: T, state: ActionState) -> bool
where
T: ToString,
{
if let Some(s) = self.actions.get(&action.to_string()) {
s == &state
} else {
false
}
}
/// This method is called every frame, by the `InputManagerSystem`.
pub fn update(&mut self, input: &InputHandler<String, String>) {
for action in input.bindings.actions() {
let state = self
.actions
.entry(action.clone())
.or_insert(ActionState::default());
if let Some(is_down) = input.action_is_down(&action) {
if is_down {
// IS DOWN
*state = match state {
// Was previously `Down` or `Pressed`, becomes or stays `Pressed`, as it is still pressed down.
ActionState::Down | ActionState::Pressed => {
ActionState::Pressed
}
// Was previously `Up` or `None`, becomes `Down`, as it is now newly pressed.
ActionState::Up | ActionState::None => {
ActionState::Down
}
};
} else {
// NOT DOWN
*state = match state {
// Was previously `Down` or `Pressed`, becomes `Up`, as it is no longer pressed.
ActionState::Down | ActionState::Pressed => {
ActionState::Up
}
// Was previously `Up` or `None`, becomes or stays `None`.
ActionState::Up | ActionState::None => {
ActionState::None
}
};
}
} else {
panic!(format!("Action should exist: {}", action));
}
}
}
}
impl Default for InputManager {
fn default() -> Self {
Self {
actions: HashMap::new(),
}
}
}