Skip to main content

cloudiful_bevy_input/
action_state.rs

1use crate::bindings::InputAction;
2use bevy::prelude::Resource;
3use std::collections::HashMap;
4
5#[derive(Debug, Clone, Copy, PartialEq)]
6pub struct ActionData {
7    pub pressed: bool,
8    pub just_pressed: bool,
9    pub just_released: bool,
10    pub value: f32,
11}
12
13impl Default for ActionData {
14    fn default() -> Self {
15        Self {
16            pressed: false,
17            just_pressed: false,
18            just_released: false,
19            value: 0.0,
20        }
21    }
22}
23
24#[derive(Resource, Debug, Clone)]
25pub struct ActionState<A: InputAction> {
26    actions: HashMap<A, ActionData>,
27}
28
29impl<A: InputAction> Default for ActionState<A> {
30    fn default() -> Self {
31        Self {
32            actions: HashMap::new(),
33        }
34    }
35}
36
37impl<A: InputAction> ActionState<A> {
38    pub fn pressed(&self, action: A) -> bool {
39        self.data(action).pressed
40    }
41
42    pub fn just_pressed(&self, action: A) -> bool {
43        self.data(action).just_pressed
44    }
45
46    pub fn just_released(&self, action: A) -> bool {
47        self.data(action).just_released
48    }
49
50    pub fn value(&self, action: A) -> f32 {
51        self.data(action).value
52    }
53
54    pub fn data(&self, action: A) -> ActionData {
55        self.actions.get(&action).copied().unwrap_or_default()
56    }
57
58    pub(crate) fn set(&mut self, action: A, data: ActionData) {
59        self.actions.insert(action, data);
60    }
61}
62
63#[derive(Resource, Debug, Clone, Copy, PartialEq)]
64pub struct InputSettings {
65    pub action_press_threshold: f32,
66    pub axis_activity_threshold: f32,
67}
68
69impl Default for InputSettings {
70    fn default() -> Self {
71        Self {
72            action_press_threshold: 0.5,
73            axis_activity_threshold: 0.2,
74        }
75    }
76}