Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding an example that uses an ActionState Resource #413

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions examples/action_state_resource.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//! Oftentimes your input actions can be handled globally and are
//! best represented as a [`Resource`].
//!
//! This example demonstrates how to create a simple `ActionLike`
//! and include it as a resource in a bevy app.

use bevy::prelude::*;
use leafwing_input_manager::{prelude::*, user_input::InputKind};

fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(InputManagerPlugin::<PlayerAction>::default())
// Initialize the ActionState resource
.init_resource::<ActionState<PlayerAction>>()
// Insert the InputMap resource
.insert_resource(PlayerAction::mkb_input_map())
.add_systems(Update, move_player)
.run();
}

#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Hash, Debug, Reflect)]
pub enum PlayerAction {
Move,
Jump,
}

// Exhaustively match `PlayerAction` and define the default binding to the input
impl PlayerAction {
fn mkb_input_map() -> InputMap<PlayerAction> {
use KeyCode::*;
InputMap::new([
(UserInput::Single(InputKind::Keyboard(Space)), Self::Jump),
(UserInput::VirtualDPad(VirtualDPad::wasd()), Self::Move),
])
}
}

fn move_player(
// action_state is stored as a resource
action_state: Res<ActionState<PlayerAction>>,
) {
if action_state.pressed(PlayerAction::Move) {
// We're working with gamepads, so we want to defensively ensure that we're using the clamped values
let axis_pair = action_state.clamped_axis_pair(PlayerAction::Move).unwrap();
println!("Move: ({}, {})", axis_pair.x(), axis_pair.y());
}

if action_state.pressed(PlayerAction::Jump) {
println!("Jumping!");
}
}