use bevy::prelude::*;
use bevy_input_bindings::prelude::*;
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
keyboard::Plugin::<MyActions, NoValues, MyKeyboardBinding>::new(),
))
.add_observer(
|action: On<ActionEvent<MyActions>>, mut binders: Query<&mut MyKeyboardBinding>| {
println!("Action from {}: {:?}", action.controller(), action.key());
let Ok(mut binder) = binders.get_mut(action.controller()) else {
return;
};
match action.key() {
MyActions::Jump => {
binder.jump_or_shoot = false;
},
MyActions::Shoot => {
binder.jump_or_shoot = true;
},
}
},
)
.add_systems(Startup, |mut commands: Commands| {
commands.spawn(Camera2d::default());
commands.spawn(MyKeyboardBinding::new());
})
.run();
}
#[derive(Debug)]
enum MyActions {
Jump,
Shoot,
}
#[derive(Debug, Hash, PartialEq, Eq)]
struct NoValues;
#[derive(Component, Reflect)]
struct MyKeyboardBinding {
jump_or_shoot: bool,
jump: keyboard::triggers::ButtonPressed,
shoot: keyboard::triggers::ButtonPressed,
}
impl MyKeyboardBinding {
fn new() -> Self {
Self {
jump_or_shoot: true,
jump: keyboard::triggers::ButtonPressed::new(KeyCode::KeyQ),
shoot: keyboard::triggers::ButtonPressed::new(KeyCode::KeyQ),
}
}
}
impl keyboard::Binding<MyActions, NoValues> for MyKeyboardBinding {
fn get_action_bindings<'a>(
&'a mut self,
) -> Vec<(&'a mut dyn keyboard::TriggerTrait, MyActions)> {
if self.jump_or_shoot {
return vec![(&mut self.jump, MyActions::Jump)];
} else {
return vec![(&mut self.shoot, MyActions::Shoot)];
}
}
}