use bevy::reflect::Reflect;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Clone, Copy, PartialEq, Reflect, Serialize, Deserialize)]
pub struct ButtonValue {
pub pressed: bool,
pub value: f32,
}
impl ButtonValue {
#[inline]
pub fn new(pressed: bool, value: f32) -> Self {
Self { pressed, value }
}
#[inline]
pub fn from_pressed(pressed: bool) -> Self {
Self::new(pressed, f32::from(pressed))
}
}
impl From<ButtonState> for ButtonValue {
fn from(state: ButtonState) -> Self {
Self::from_pressed(state.pressed())
}
}
impl From<bevy::input::ButtonState> for ButtonValue {
fn from(state: bevy::input::ButtonState) -> Self {
Self::from_pressed(state.is_pressed())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Reflect, Default)]
pub enum ButtonState {
JustPressed,
Pressed,
JustReleased,
#[default]
Released,
}
impl ButtonState {
pub fn tick(&mut self) {
use ButtonState::*;
*self = match self {
JustPressed => Pressed,
Pressed => Pressed,
JustReleased => Released,
Released => Released,
}
}
#[inline]
pub fn press(&mut self) {
if *self != ButtonState::Pressed {
*self = ButtonState::JustPressed;
}
}
#[inline]
pub fn release(&mut self) {
if *self != ButtonState::Released {
*self = ButtonState::JustReleased;
}
}
#[inline]
#[must_use]
pub fn pressed(&self) -> bool {
*self == ButtonState::Pressed || *self == ButtonState::JustPressed
}
#[inline]
#[must_use]
pub fn released(&self) -> bool {
*self == ButtonState::Released || *self == ButtonState::JustReleased
}
#[inline]
#[must_use]
pub fn just_pressed(&self) -> bool {
*self == ButtonState::JustPressed
}
#[inline]
#[must_use]
pub fn just_released(&self) -> bool {
*self == ButtonState::JustReleased
}
}