Skip to content
Snippets Groups Projects
player.rs 1.17 KiB
Newer Older
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;
		}
	}
}