bevy_input_bindings 0.0.2

High level, flexible and shareable input binding library for the Bevy game engine
Documentation
use bevy::ecs::component::Component;
use std::collections::HashMap;

/// A variant specifically made for controller values.
#[derive(Debug, Clone)]
pub enum VariantValue {
    None,
    Bool(bool),
    Axis1d(f32),
    Axis2d(f32, f32),
}

/// `ControllerValues` is the component that holds all the reported values. It is added alongside
/// all the `ControllerInterface` so systems can query it.
#[derive(Component)]
pub struct ControllerValues<ValueKey>
where
    ValueKey: std::hash::Hash + PartialEq + Eq + Sync + Send + 'static,
{
    pub(crate) values: HashMap<ValueKey, VariantValue>,
}

impl<ValueKey> ControllerValues<ValueKey>
where
    ValueKey: std::hash::Hash + PartialEq + Eq + Sync + Send + 'static,
{
    /// Create a new empty `ControllerValues`.
    pub(crate) fn new() -> Self {
        Self {
            values: HashMap::new(),
        }
    }

    /// Get access to a specific value.
    ///
    /// A `None` value would mean no such value has been reported yet.
    pub fn get<'a>(&'a self, key: &ValueKey) -> Option<&'a VariantValue> {
        return self.values.get(key);
    }

    /// Get access to a specific value as a boolean.
    ///
    /// A `None` value would mean no such value has been reported yet or is not the right type.
    pub fn get_as_bool(&self, key: &ValueKey) -> Option<bool> {
        match self.values.get(key) {
            Some(VariantValue::Bool(value)) => Some(*value),
            _ => None,
        }
    }

    /// Get access to a specific value as a boolean.
    ///
    /// A `None` value would mean no such value has been reported yet or is not the right type.
    pub fn get_as_axis1d(&self, key: &ValueKey) -> Option<f32> {
        match self.values.get(key) {
            Some(VariantValue::Axis1d(value)) => Some(*value),
            _ => None,
        }
    }

    /// Get access to a specific value as a boolean.
    ///
    /// A `None` value would mean no such value has been reported yet or is not the right type.
    pub fn get_as_axis2d(&self, key: &ValueKey) -> Option<(f32, f32)> {
        match self.values.get(key) {
            Some(VariantValue::Axis2d(value0, value1)) => Some((*value0, *value1)),
            _ => None,
        }
    }
}