use bevy::prelude::*;
use leafwing_input_manager::{prelude::*, user_input::InputKind};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(InputManagerPlugin::<PlayerAction>::default())
.add_systems(Startup, spawn_player)
.add_systems(Update, use_actions)
.run()
}
#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Hash, Debug, Reflect)]
enum PlayerAction {
Run,
Jump,
UseItem,
}
impl PlayerAction {
fn variants() -> &'static [PlayerAction] {
&[Self::Run, Self::Jump, Self::UseItem]
}
}
impl PlayerAction {
fn default_keyboard_mouse_input(&self) -> UserInput {
match self {
Self::Run => UserInput::VirtualDPad(VirtualDPad::wasd()),
Self::Jump => UserInput::Single(InputKind::PhysicalKey(KeyCode::Space)),
Self::UseItem => UserInput::Single(InputKind::Mouse(MouseButton::Left)),
}
}
fn default_gamepad_input(&self) -> UserInput {
match self {
Self::Run => UserInput::Single(InputKind::DualAxis(DualAxis::left_stick())),
Self::Jump => UserInput::Single(InputKind::GamepadButton(GamepadButtonType::South)),
Self::UseItem => {
UserInput::Single(InputKind::GamepadButton(GamepadButtonType::RightTrigger2))
}
}
}
}
#[derive(Component)]
struct Player;
fn spawn_player(mut commands: Commands) {
let mut input_map = InputMap::default();
for action in PlayerAction::variants() {
input_map.insert(*action, PlayerAction::default_keyboard_mouse_input(action));
input_map.insert(*action, PlayerAction::default_gamepad_input(action));
}
commands
.spawn(InputManagerBundle::<PlayerAction> {
input_map,
..default()
})
.insert(Player);
}
fn use_actions(query: Query<&ActionState<PlayerAction>, With<Player>>) {
let action_state = query.single();
if action_state.pressed(&PlayerAction::Run) {
println!(
"Moving in direction {}",
action_state
.clamped_axis_pair(&PlayerAction::Run)
.unwrap()
.xy()
);
}
if action_state.just_pressed(&PlayerAction::Jump) {
println!("Jumped!");
}
if action_state.just_pressed(&PlayerAction::UseItem) {
println!("Used an Item!");
}
}