input_actions/action/
state.rs

1use crate::{action, event, source};
2use std::time::Instant;
3
4/// The state of an active [`action`](action::Action) for a given user.
5#[derive(Debug, Clone)]
6pub struct State {
7	kind: source::Kind,
8	behavior: action::Behavior,
9	/// Used to indicate if a button is pressed or released
10	prev_frame_active: bool,
11	active: bool,
12	active_state_changed_this_frame: bool,
13	value: f32,
14	modified_at: Instant,
15}
16
17impl State {
18	pub(crate) fn new(action: action::Action) -> Self {
19		Self {
20			kind: action.kind(),
21			behavior: action.behavior().clone(),
22			prev_frame_active: false,
23			active: false,
24			active_state_changed_this_frame: false,
25			value: 0.0,
26			modified_at: Instant::now(),
27		}
28	}
29
30	pub(crate) fn process_event(&mut self, event: event::Event, time: &Instant) {
31		if match event.state {
32			event::State::ButtonState(btn_state) => {
33				let is_active = btn_state == event::ButtonState::Pressed;
34				if self.active != is_active {
35					self.active = is_active;
36					true
37				} else {
38					false
39				}
40			}
41			event::State::MouseMove(_x, _y) => false,
42			event::State::MouseScroll(_x, _y) => false,
43			event::State::ValueChanged(value) => {
44				if self.kind == source::Kind::Axis {
45					if event.source.kind() == source::Kind::Button {
46						// TODO: Handle digitial axis
47					}
48				}
49				self.value = value;
50				true
51			}
52		} {
53			self.modified_at = *time;
54		}
55	}
56
57	pub(crate) fn requires_updates(&self) -> bool {
58		true //self.behavior.digital_axis().is_some()
59	}
60
61	pub(crate) fn update(&mut self, _time: &Instant) {
62		self.active_state_changed_this_frame = self.active != self.prev_frame_active;
63		if self.active_state_changed_this_frame {
64			self.prev_frame_active = self.active;
65		}
66	}
67
68	/// Returns true when a [`button binding`](crate::source::Kind::Button) is pressed,
69	/// and this function is called in the same update frame as the input event which pressed the button.
70	pub fn on_button_pressed(&self) -> bool {
71		self.active && self.active_state_changed_this_frame
72	}
73
74	/// Returns true when a [`button binding`](crate::source::Kind::Button) is not pressed,
75	/// and this function is called in the same update frame as the input event which released the button.
76	pub fn on_button_released(&self) -> bool {
77		!self.active && self.active_state_changed_this_frame
78	}
79}