1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use bevy::prelude::*;
use bevy_input_bindings::prelude::*;
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
// Add the keyboard plugin attached to the custom binder
keyboard::Plugin::<MyActions, NoValues, MyKeyboardBinding>::new(),
))
// Add an observer to print the inputs. It will catch events for the `MyActions` actions,
// find the `ControllerInterface` that sent it, and print the event data.
.add_observer(|action: On<ActionEvent<MyActions>>, players: Query<(&Name, &Player)>| {
for (name, player) in players {
// Filter the unrelated controllers out
if !player.controllers.contains(&action.controller()) {
continue;
}
// Print the jumps
match action.key() {
MyActions::Jump => {
println!("{} jump", name);
},
}
}
})
// Add a startup system to initiate the entities
.add_systems(Startup, |mut commands: Commands| {
commands.spawn(Camera3d::default());
// Here we instantiate two binders with different bindings so a single player can play
// on two controllers.
let controller_1_id = commands.spawn(MyKeyboardBinding::new(KeyCode::KeyQ)).id();
let controller_2_id = commands.spawn(MyKeyboardBinding::new(KeyCode::KeyW)).id();
// Instantiate a third controller that won't control the player.
commands.spawn(MyKeyboardBinding::new(KeyCode::KeyE));
// Instantiate a player that knows which controller are controlling it.
// As the player will be controlled by both controllers, `ControlledBy` can't be used.
commands.spawn((
Player {
controllers: vec![controller_1_id, controller_2_id],
},
Name::new("John Doe"),
));
})
.run();
}
#[derive(Component)]
struct Player {
controllers: Vec<Entity>,
}
/// Custom actions for this example
#[derive(Debug)]
enum MyActions {
Jump,
}
/// Custom values for this example
#[derive(Debug, Hash, PartialEq, Eq)]
struct NoValues;
/// Custom binder for this example
#[derive(Component, Reflect)]
struct MyKeyboardBinding {
jump: keyboard::triggers::ButtonPressed,
}
impl MyKeyboardBinding {
fn new(jump: KeyCode) -> Self {
Self {
jump: keyboard::triggers::ButtonPressed::new(jump),
}
}
}
impl keyboard::Binding<MyActions, NoValues> for MyKeyboardBinding {
fn get_action_bindings<'a>(
&'a mut self,
) -> Vec<(&'a mut dyn keyboard::TriggerTrait, MyActions)> {
return vec![(&mut self.jump, MyActions::Jump)];
}
}