blackout/src/navigation.rs

280 lines
9.0 KiB
Rust

use std::{collections::HashMap, error::Error, fmt::Debug, hash::Hash, marker::PhantomData};
use bevy::prelude::*;
use bevy_input_actionmap::InputMap;
use bevy_rapier2d::{na::UnitComplex, prelude::*};
use bevy_tts::Tts;
use derive_more::{Deref, DerefMut};
use crate::{
core::{Angle, CardinalDirection, Player},
error::error_handler,
exploration::{ExplorationFocused, Exploring},
pathfinding::Destination,
};
#[derive(Clone, Copy, Debug, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct MaxSpeed(pub f32);
impl Default for MaxSpeed {
fn default() -> Self {
MaxSpeed(2.)
}
}
#[derive(Clone, Copy, Debug, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct RotationSpeed(pub Angle);
impl Default for RotationSpeed {
fn default() -> Self {
Self(Angle::Radians(0.))
}
}
#[derive(Clone, Copy, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct Speed(pub f32);
#[derive(Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct Sprinting;
fn movement_controls<S, A: 'static>(
mut commands: Commands,
config: Res<NavigationConfig<S, A>>,
input: Res<InputMap<A>>,
time: Res<Time>,
mut query: Query<
(
Entity,
&mut RigidBodyVelocity,
&mut Speed,
&MaxSpeed,
Option<&RotationSpeed>,
&mut RigidBodyPosition,
Option<&Destination>,
),
With<Player>,
>,
exploration_focused: Query<(Entity, &ExplorationFocused)>,
) where
S: bevy::ecs::component::Component + Clone + Debug + Eq + Hash,
A: Hash + Eq + Clone + Send + Sync,
{
for (entity, mut velocity, mut speed, max_speed, rotation_speed, mut position, destination) in
query.iter_mut()
{
let sprinting = if let Some(action) = config.action_sprint.clone() {
input.active(action)
} else {
false
};
if sprinting {
commands.entity(entity).insert(Sprinting::default());
} else {
commands.entity(entity).remove::<Sprinting>();
}
let mut direction = Vec2::default();
if let Some(action) = config.action_forward.clone() {
if input.active(action) {
direction.x += 1.;
}
}
if let Some(action) = config.action_backward.clone() {
if input.active(action) {
direction.x -= 1.;
}
}
if let Some(action) = config.action_left.clone() {
if input.active(action) {
direction.y += 1.;
}
}
if let Some(action) = config.action_right.clone() {
if input.active(action) {
direction.y -= 1.;
}
}
if let (Some(rotation_speed), Some(rotate_left), Some(rotate_right)) = (
rotation_speed,
config.action_rotate_left.clone(),
config.action_rotate_right.clone(),
) {
let delta = rotation_speed.radians() * time.delta_seconds();
if input.active(rotate_left) {
position.position.rotation *= UnitComplex::new(delta);
}
if input.active(rotate_right) {
position.position.rotation *= UnitComplex::new(-delta);
} else {
velocity.angvel = 0.;
}
} else {
velocity.angvel = 0.;
}
if direction.length_squared() != 0. {
commands.entity(entity).remove::<Destination>();
commands.entity(entity).remove::<Exploring>();
for (entity, _) in exploration_focused.iter() {
commands.entity(entity).remove::<ExplorationFocused>();
}
direction = direction.normalize();
if direction.x > 0. {
direction.x *= config.forward_movement_factor;
} else if direction.x < 0. {
direction.x *= config.backward_movement_factor;
}
if direction.y != 0. {
direction.y *= config.strafe_movement_factor;
}
let strength = if let (Some(forward), Some(backward), Some(left), Some(right)) = (
config.action_forward.clone(),
config.action_backward.clone(),
config.action_left.clone(),
config.action_right.clone(),
) {
let forward_x = input.strength(forward).abs();
let backward_x = input.strength(backward).abs();
let x = if forward_x > backward_x {
forward_x
} else {
backward_x
};
let right_y = input.strength(right).abs();
let left_y = input.strength(left).abs();
let y = if right_y > left_y { right_y } else { left_y };
Some(Vec2::new(x, y))
} else {
None
};
let s = if sprinting {
**max_speed
} else {
**max_speed / config.sprint_movement_factor
};
**speed = s;
if let Some(strength) = strength {
direction *= strength;
}
let mut v: Vector<Real> = (direction * **speed).into();
v = position.position.rotation.transform_vector(&v);
velocity.linvel = v;
//velocity.linvel = position.position.rotation.transform_vector(&velocity.linvel);
} else if destination.is_none() {
velocity.linvel = Vec2::ZERO.into();
**speed = 0.;
} else if sprinting {
**speed = **max_speed;
} else {
velocity.linvel = Vec2::ZERO.into();
**speed = **max_speed / 3.;
}
}
}
fn update_direction(
mut commands: Commands,
query: Query<
(Entity, &Transform, Option<&CardinalDirection>),
(With<Player>, Changed<Transform>),
>,
) {
for (entity, transform, direction) in query.iter() {
let forward = transform.local_x();
let yaw = Angle::Radians(forward.y.atan2(forward.x));
let new_direction: CardinalDirection = yaw.into();
if direction != Some(&new_direction) {
commands.entity(entity).insert(new_direction);
}
}
}
fn speak_direction(
mut tts: ResMut<Tts>,
player: Query<&CardinalDirection, (With<Player>, Changed<CardinalDirection>)>,
) -> Result<(), Box<dyn Error>> {
if let Ok(direction) = player.single() {
let direction: String = (*direction).into();
tts.speak(direction, true)?;
}
Ok(())
}
#[derive(Clone, Debug)]
pub struct NavigationConfig<S, A> {
pub action_backward: Option<A>,
pub action_forward: Option<A>,
pub action_left: Option<A>,
pub action_right: Option<A>,
pub action_rotate_left: Option<A>,
pub action_rotate_right: Option<A>,
pub action_sprint: Option<A>,
pub forward_movement_factor: f32,
pub backward_movement_factor: f32,
pub strafe_movement_factor: f32,
pub sprint_movement_factor: f32,
pub movement_control_states: Vec<S>,
}
impl<S, A> Default for NavigationConfig<S, A> {
fn default() -> Self {
Self {
action_backward: None,
action_forward: None,
action_left: None,
action_right: None,
action_rotate_left: None,
action_rotate_right: None,
action_sprint: None,
forward_movement_factor: 1.,
backward_movement_factor: 1.,
strafe_movement_factor: 1.,
sprint_movement_factor: 3.,
movement_control_states: vec![],
}
}
}
pub struct NavigationPlugin<'a, S, A>(PhantomData<&'a S>, PhantomData<&'a A>);
impl<'a, S, A> Default for NavigationPlugin<'a, S, A> {
fn default() -> Self {
Self(PhantomData, PhantomData)
}
}
impl<'a, S, A> Plugin for NavigationPlugin<'a, S, A>
where
S: bevy::ecs::component::Component + Clone + Debug + Eq + Hash,
A: Hash + Eq + Clone + Send + Sync,
'a: 'static,
{
fn build(&self, app: &mut AppBuilder) {
if !app.world().contains_resource::<NavigationConfig<S, A>>() {
app.insert_resource(NavigationConfig::<S, A>::default());
}
let config = app
.world()
.get_resource::<NavigationConfig<S, A>>()
.unwrap()
.clone();
app.register_type::<MaxSpeed>()
.register_type::<RotationSpeed>()
.register_type::<Sprinting>()
.add_system(update_direction.system())
.add_system(speak_direction.system().chain(error_handler.system()));
if config.movement_control_states.is_empty() {
app.add_system(movement_controls::<S, A>.system());
} else {
let states = config.movement_control_states;
for state in states {
app.add_system_set(
SystemSet::on_update(state).with_system(movement_controls::<S, A>.system()),
);
}
}
}
}