bevy_input_bindings 0.0.2

High level, flexible and shareable input binding library for the Bevy game engine
Documentation
use std::time::Duration;

use bevy::input::ButtonInput;
use bevy::input::keyboard::KeyCode;
use bevy::reflect::Reflect;

use crate::controller_values::VariantValue;

pub trait FunctionTrait {
    fn update_value(
        &mut self,
        button_input: &ButtonInput<KeyCode>,
        dt: &Duration,
        value: &mut VariantValue,
    );
}

#[derive(Reflect, Clone, Debug)]
pub struct ButtonPressed {
    key: KeyCode,
}

impl ButtonPressed {
    pub fn new(key: KeyCode) -> Self {
        Self {
            key,
        }
    }
}

impl FunctionTrait for ButtonPressed {
    fn update_value(
        &mut self,
        button_input: &ButtonInput<KeyCode>,
        _dt: &Duration,
        value: &mut VariantValue,
    ) {
        *value = VariantValue::Bool(button_input.pressed(self.key));
    }
}

#[derive(Reflect, Clone, Debug)]
pub struct Arrows {
    up: KeyCode,
    down: KeyCode,
    left: KeyCode,
    right: KeyCode,
}

impl Arrows {
    pub fn new(up: KeyCode, down: KeyCode, left: KeyCode, right: KeyCode) -> Self {
        Self {
            up,
            down,
            left,
            right,
        }
    }
}

impl FunctionTrait for Arrows {
    fn update_value(
        &mut self,
        button_input: &ButtonInput<KeyCode>,
        _dt: &Duration,
        value: &mut VariantValue,
    ) {
        let mut axis_x = 0.0;
        let mut axis_y = 0.0;
        if button_input.pressed(self.up) {
            axis_y += 1.0;
        }
        if button_input.pressed(self.down) {
            axis_y -= 1.0;
        }
        if button_input.pressed(self.left) {
            axis_x += 1.0;
        }
        if button_input.pressed(self.right) {
            axis_x -= 1.0;
        }
        *value = VariantValue::Axis2d(axis_x, axis_y);
    }
}