generated from Leafwing-Studios/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 122
/
multiplayer.rs
83 lines (74 loc) · 2.36 KB
/
multiplayer.rs
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
use bevy::prelude::*;
use leafwing_input_manager::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(InputManagerPlugin::<Action>::default())
.add_systems(Startup, spawn_players)
.run();
}
#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Hash, Debug, Reflect)]
enum Action {
Left,
Right,
Jump,
}
#[derive(Component)]
enum Player {
One,
Two,
}
#[derive(Bundle)]
struct PlayerBundle {
player: Player,
input_manager: InputManagerBundle<Action>,
}
impl PlayerBundle {
fn input_map(player: Player) -> InputMap<Action> {
let mut input_map = match player {
Player::One => InputMap::new([
(KeyCode::A, Action::Left),
(KeyCode::D, Action::Right),
(KeyCode::W, Action::Jump),
])
// This is a quick and hacky solution:
// you should coordinate with the `Gamepads` resource to determine the correct gamepad for each player
// and gracefully handle disconnects
// Note that this step is not required:
// if it is skipped all input maps will read from all connected gamepads
.set_gamepad(Gamepad { id: 0 })
.build(),
Player::Two => InputMap::new([
(KeyCode::Left, Action::Left),
(KeyCode::Right, Action::Right),
(KeyCode::Up, Action::Jump),
])
.set_gamepad(Gamepad { id: 1 })
.build(),
};
// Each player will use the same gamepad controls, but on separate gamepads.
input_map.insert_multiple([
(GamepadButtonType::DPadLeft, Action::Left),
(GamepadButtonType::DPadRight, Action::Right),
(GamepadButtonType::DPadUp, Action::Jump),
(GamepadButtonType::South, Action::Jump),
]);
input_map
}
}
fn spawn_players(mut commands: Commands) {
commands.spawn(PlayerBundle {
player: Player::One,
input_manager: InputManagerBundle {
input_map: PlayerBundle::input_map(Player::One),
..Default::default()
},
});
commands.spawn(PlayerBundle {
player: Player::Two,
input_manager: InputManagerBundle {
input_map: PlayerBundle::input_map(Player::Two),
..Default::default()
},
});
}