use bevy_ecs::resource::Resource;
use bevy_platform::collections::HashMap;
use core::hash::Hash;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
#[derive(Debug, Resource)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub struct Axis<T> {
axis_data: HashMap<T, f32>,
}
impl<T> Default for Axis<T>
where
T: Copy + Eq + Hash,
{
fn default() -> Self {
Axis {
axis_data: HashMap::default(),
}
}
}
impl<T> Axis<T>
where
T: Copy + Eq + Hash,
{
pub const MIN: f32 = -1.0;
pub const MAX: f32 = 1.0;
pub fn set(&mut self, input_device: impl Into<T>, position_data: f32) -> Option<f32> {
self.axis_data.insert(input_device.into(), position_data)
}
pub fn get(&self, input_device: impl Into<T>) -> Option<f32> {
self.axis_data
.get(&input_device.into())
.copied()
.map(|value| value.clamp(Self::MIN, Self::MAX))
}
pub fn get_unclamped(&self, input_device: impl Into<T>) -> Option<f32> {
self.axis_data.get(&input_device.into()).copied()
}
pub fn remove(&mut self, input_device: impl Into<T>) -> Option<f32> {
self.axis_data.remove(&input_device.into())
}
pub fn all_axes(&self) -> impl Iterator<Item = &T> {
self.axis_data.keys()
}
pub fn all_axes_and_values(&self) -> impl Iterator<Item = (&T, f32)> {
self.axis_data.iter().map(|(axis, value)| (axis, *value))
}
}
#[cfg(test)]
mod tests {
use crate::{gamepad::GamepadButton, Axis};
#[test]
fn test_axis_set() {
let cases = [
(-1.5, Some(-1.0)),
(-1.1, Some(-1.0)),
(-1.0, Some(-1.0)),
(-0.9, Some(-0.9)),
(-0.1, Some(-0.1)),
(0.0, Some(0.0)),
(0.1, Some(0.1)),
(0.9, Some(0.9)),
(1.0, Some(1.0)),
(1.1, Some(1.0)),
(1.6, Some(1.0)),
];
for (value, expected) in cases {
let mut axis = Axis::<GamepadButton>::default();
axis.set(GamepadButton::RightTrigger, value);
let actual = axis.get(GamepadButton::RightTrigger);
assert_eq!(expected, actual);
}
}
#[test]
fn test_axis_remove() {
let cases = [-1.0, -0.9, -0.1, 0.0, 0.1, 0.9, 1.0];
for value in cases {
let mut axis = Axis::<GamepadButton>::default();
axis.set(GamepadButton::RightTrigger, value);
assert!(axis.get(GamepadButton::RightTrigger).is_some());
axis.remove(GamepadButton::RightTrigger);
let actual = axis.get(GamepadButton::RightTrigger);
let expected = None;
assert_eq!(expected, actual);
}
}
}