beet_examples/components/
keyboard_controller.rs1use bevy::prelude::*;
2
3#[derive(Component, Reflect)]
4#[reflect(Default, Component)]
5pub struct KeyboardController {
6 pub speed: f32,
7}
8
9impl Default for KeyboardController {
10 fn default() -> Self { Self { speed: 3. } }
11}
12
13pub fn keyboard_controller(
14 time: Res<Time>,
15 keys: Res<ButtonInput<KeyCode>>,
16 mut query: Populated<(&mut Transform, &KeyboardController)>,
17) {
18 for (mut transform, controller) in query.iter_mut() {
19 let mut direction = Vec3::ZERO;
20 if keys.pressed(KeyCode::KeyW) {
21 direction -= Vec3::Z;
22 }
23 if keys.pressed(KeyCode::KeyS) {
24 direction += Vec3::Z;
25 }
26 if keys.pressed(KeyCode::KeyA) {
27 direction -= Vec3::X;
28 }
29 if keys.pressed(KeyCode::KeyD) {
30 direction += Vec3::X;
31 }
32 if keys.pressed(KeyCode::KeyR) {
33 direction += Vec3::Y;
34 }
35 if keys.pressed(KeyCode::KeyF) {
36 direction -= Vec3::Y;
37 }
38 transform.translation +=
39 direction * controller.speed * time.delta_secs();
40 }
41}