Newer
Older
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
use crate::entities::spawning::EntitySpawner;
use crate::entities::Velocity;
use crate::system::window_bounds;
use bevy::math::Vec2;
use bevy::prelude::{Component, DetectChangesMut, Input, KeyCode, Query, Res, With};
#[derive(Component)]
pub struct Player;
pub fn spawn_player(mut spawner: EntitySpawner) {
let bounds = window_bounds();
spawner.spawn_player_at(bounds.half_size());
}
macro_rules! any_pressed {
($input: expr, $key: expr $(, $more: expr),*) => {$input.pressed($key) $(|| any_pressed!($input, $more))*};
}
pub fn process_player_input(
mut player_query: Query<&mut Velocity, With<Player>>,
input: Res<Input<KeyCode>>,
) {
let mut delta = Vec2::default();
if any_pressed!(input, KeyCode::A, KeyCode::Left) {
delta.x -= 1.0;
}
if any_pressed!(input, KeyCode::D, KeyCode::Right) {
delta.x += 1.0;
}
if any_pressed!(input, KeyCode::S, KeyCode::Down) {
delta.y -= 1.0;
}
if any_pressed!(input, KeyCode::W, KeyCode::Up) {
delta.y += 1.0;
}
for mut velocity in &mut player_query {
if delta != Vec2::ZERO {
*velocity = Velocity::default() * delta;
} else if **(velocity.bypass_change_detection()) != Vec2::ZERO {
*velocity = Velocity::ZERO;
}
}
}