bevy_enhanced_input/input_condition/
release.rs

1use bevy::prelude::*;
2
3use super::{DEFAULT_ACTUATION, InputCondition};
4use crate::{
5    action_map::{ActionMap, ActionState},
6    action_value::ActionValue,
7};
8
9/// Returns [`ActionState::Ongoing`]` when the input exceeds the actuation threshold and
10/// [`ActionState::Fired`] once when the input drops back below the actuation threshold.
11#[derive(Clone, Copy, Debug)]
12pub struct Release {
13    /// Trigger threshold.
14    pub actuation: f32,
15    actuated: bool,
16}
17
18impl Release {
19    #[must_use]
20    pub fn new(actuation: f32) -> Self {
21        Self {
22            actuation,
23            actuated: false,
24        }
25    }
26}
27
28impl Default for Release {
29    fn default() -> Self {
30        Self::new(DEFAULT_ACTUATION)
31    }
32}
33
34impl InputCondition for Release {
35    fn evaluate(
36        &mut self,
37        _action_map: &ActionMap,
38        _time: &Time<Virtual>,
39        value: ActionValue,
40    ) -> ActionState {
41        let previously_actuated = self.actuated;
42        self.actuated = value.is_actuated(self.actuation);
43
44        if self.actuated {
45            // Ongoing on hold.
46            ActionState::Ongoing
47        } else if previously_actuated {
48            // Fired on release.
49            ActionState::Fired
50        } else {
51            ActionState::None
52        }
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn release() {
62        let mut condition = Release::default();
63        let action_map = ActionMap::default();
64        let time = Time::default();
65
66        assert_eq!(
67            condition.evaluate(&action_map, &time, 0.0.into()),
68            ActionState::None
69        );
70        assert_eq!(
71            condition.evaluate(&action_map, &time, 1.0.into()),
72            ActionState::Ongoing
73        );
74        assert_eq!(
75            condition.evaluate(&action_map, &time, 0.0.into()),
76            ActionState::Fired
77        );
78    }
79}