forked from sburris0/bevy_flycam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
163 lines (146 loc) · 5.29 KB
/
lib.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use bevy::ecs::event::{Events, ManualEventReader};
use bevy::input::mouse::MouseMotion;
use bevy::prelude::*;
/// Keeps track of mouse motion events, pitch, and yaw
#[derive(Default)]
struct InputState {
reader_motion: ManualEventReader<MouseMotion>,
pitch: f32,
yaw: f32,
}
/// Mouse sensitivity and movement speed
pub struct MovementSettings {
pub sensitivity: f32,
pub speed: f32,
}
impl Default for MovementSettings {
fn default() -> Self {
Self {
sensitivity: 0.00012,
speed: 12.,
}
}
}
/// A marker component used in queries when you want flycams and not other cameras
#[derive(Component)]
pub struct FlyCam;
/// Grabs/ungrabs mouse cursor
fn toggle_grab_cursor(window: &mut Window) {
window.set_cursor_lock_mode(!window.cursor_locked());
window.set_cursor_visibility(!window.cursor_visible());
}
/// Grabs the cursor when game first starts
fn initial_grab_cursor(mut windows: ResMut<Windows>) {
if let Some(window) = windows.get_primary_mut() {
toggle_grab_cursor(window);
} else {
warn!("Primary window not found for `initial_grab_cursor`!");
}
}
/// Spawns the `Camera3dBundle` to be controlled
fn setup_player(mut commands: Commands) {
commands
.spawn_bundle(Camera3dBundle {
transform: Transform::from_xyz(-2.0, 5.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
..Default::default()
})
.insert(FlyCam);
}
/// Handles keyboard input and movement
fn player_move(
keys: Res<Input<KeyCode>>,
time: Res<Time>,
windows: Res<Windows>,
settings: Res<MovementSettings>,
mut query: Query<&mut Transform, With<FlyCam>>,
) {
if let Some(window) = windows.get_primary() {
for mut transform in query.iter_mut() {
let mut velocity = Vec3::ZERO;
let local_z = transform.local_z();
let forward = -Vec3::new(local_z.x, 0., local_z.z);
let right = Vec3::new(local_z.z, 0., -local_z.x);
for key in keys.get_pressed() {
if window.cursor_locked() {
match key {
KeyCode::W => velocity += forward,
KeyCode::S => velocity -= forward,
KeyCode::A => velocity -= right,
KeyCode::D => velocity += right,
KeyCode::Space => velocity += Vec3::Y,
KeyCode::LShift => velocity -= Vec3::Y,
_ => (),
}
}
}
velocity = velocity.normalize_or_zero();
transform.translation += velocity * time.delta_seconds() * settings.speed
}
} else {
warn!("Primary window not found for `player_move`!");
}
}
/// Handles looking around if cursor is locked
fn player_look(
settings: Res<MovementSettings>,
windows: Res<Windows>,
mut state: ResMut<InputState>,
motion: Res<Events<MouseMotion>>,
mut query: Query<&mut Transform, With<FlyCam>>,
) {
if let Some(window) = windows.get_primary() {
let mut delta_state = state.as_mut();
for mut transform in query.iter_mut() {
for ev in delta_state.reader_motion.iter(&motion) {
if window.cursor_locked() {
// Using smallest of height or width ensures equal vertical and horizontal sensitivity
let window_scale = window.height().min(window.width());
delta_state.pitch -=
(settings.sensitivity * ev.delta.y * window_scale).to_radians();
delta_state.yaw -=
(settings.sensitivity * ev.delta.x * window_scale).to_radians();
}
delta_state.pitch = delta_state.pitch.clamp(-1.54, 1.54);
// Order is important to prevent unintended roll
transform.rotation = Quat::from_axis_angle(Vec3::Y, delta_state.yaw)
* Quat::from_axis_angle(Vec3::X, delta_state.pitch);
}
}
} else {
warn!("Primary window not found for `player_look`!");
}
}
fn cursor_grab(keys: Res<Input<KeyCode>>, mut windows: ResMut<Windows>) {
if let Some(window) = windows.get_primary_mut() {
if keys.just_pressed(KeyCode::Escape) {
toggle_grab_cursor(window);
}
} else {
warn!("Primary window not found for `cursor_grab`!");
}
}
/// Contains everything needed to add first-person fly camera behavior to your game
pub struct PlayerPlugin;
impl Plugin for PlayerPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<InputState>()
.init_resource::<MovementSettings>()
.add_startup_system(setup_player)
.add_startup_system(initial_grab_cursor)
.add_system(player_move)
.add_system(player_look)
.add_system(cursor_grab);
}
}
/// Same as [`PlayerPlugin`] but does not spawn a camera
pub struct NoCameraPlayerPlugin;
impl Plugin for NoCameraPlayerPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<InputState>()
.init_resource::<MovementSettings>()
.add_startup_system(initial_grab_cursor)
.add_system(player_move)
.add_system(player_look)
.add_system(cursor_grab);
}
}