blackout/src/navigation.rs

277 lines
9.0 KiB
Rust
Raw Normal View History

2021-05-26 21:46:20 +00:00
use std::{collections::HashMap, error::Error, fmt::Debug, hash::Hash, marker::PhantomData};
2021-05-13 17:25:45 +00:00
use bevy::prelude::*;
use bevy_input_actionmap::InputMap;
2021-06-03 14:04:48 +00:00
use bevy_rapier2d::{na::UnitComplex, prelude::*};
2021-05-13 17:25:45 +00:00
use bevy_tts::Tts;
use derive_more::{Deref, DerefMut};
use crate::{
core::{Angle, CardinalDirection, Player},
2021-05-13 17:25:45 +00:00
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;
2021-05-26 21:46:20 +00:00
fn movement_controls<S, A: 'static>(
2021-05-13 17:25:45 +00:00
mut commands: Commands,
2021-05-26 21:46:20 +00:00
config: Res<NavigationConfig<S, A>>,
input: Res<InputMap<A>>,
2021-05-13 17:25:45 +00:00
time: Res<Time>,
mut query: Query<
(
Entity,
&mut RigidBodyVelocity,
&mut Speed,
&MaxSpeed,
Option<&RotationSpeed>,
2021-06-03 14:04:48 +00:00
&mut RigidBodyPosition,
Option<&Destination>,
),
With<Player>,
>,
2021-05-13 17:25:45 +00:00
exploration_focused: Query<(Entity, &ExplorationFocused)>,
2021-05-26 21:46:20 +00:00
) where
S: bevy::ecs::component::Component + Clone + Debug + Eq + Hash,
A: Hash + Eq + Clone + Send + Sync,
{
2021-06-03 14:04:48 +00:00
for (entity, mut velocity, mut speed, max_speed, rotation_speed, mut position, destination) in
query.iter_mut()
2021-05-13 17:25:45 +00:00
{
2021-05-26 21:46:20 +00:00
let sprinting = if let Some(action) = config.action_sprint.clone() {
input.active(action)
} else {
false
};
2021-05-13 17:25:45 +00:00
if sprinting {
commands.entity(entity).insert(Sprinting::default());
} else {
commands.entity(entity).remove::<Sprinting>();
}
2021-06-03 14:04:48 +00:00
let mut direction = Vec2::default();
2021-05-26 21:46:20 +00:00
if let Some(action) = config.action_forward.clone() {
if input.active(action) {
direction.x += 1.;
}
2021-05-13 17:25:45 +00:00
}
2021-05-26 21:46:20 +00:00
if let Some(action) = config.action_backward.clone() {
if input.active(action) {
direction.x -= 1.;
}
2021-05-13 17:25:45 +00:00
}
2021-05-26 21:46:20 +00:00
if let Some(action) = config.action_left.clone() {
if input.active(action) {
direction.y += 1.;
}
2021-05-13 17:25:45 +00:00
}
2021-05-26 21:46:20 +00:00
if let Some(action) = config.action_right.clone() {
if input.active(action) {
direction.y -= 1.;
}
2021-05-13 17:25:45 +00:00
}
2021-05-26 21:46:20 +00:00
if let (Some(rotation_speed), Some(rotate_left), Some(rotate_right)) = (
rotation_speed,
config.action_rotate_left.clone(),
config.action_rotate_right.clone(),
) {
2021-05-13 17:25:45 +00:00
let delta = rotation_speed.radians() * time.delta_seconds();
2021-05-26 21:46:20 +00:00
if input.active(rotate_left) {
2021-06-03 14:04:48 +00:00
position.position.rotation *= UnitComplex::new(delta);
2021-05-13 17:25:45 +00:00
}
2021-05-26 21:46:20 +00:00
if input.active(rotate_right) {
2021-06-03 14:04:48 +00:00
position.position.rotation *= UnitComplex::new(-delta);
2021-05-13 17:25:45 +00:00
}
}
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>();
}
2021-05-13 17:25:45 +00:00
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;
}
2021-05-26 21:46:20 +00:00
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))
2021-05-13 17:25:45 +00:00
} else {
2021-05-26 21:46:20 +00:00
None
2021-05-13 17:25:45 +00:00
};
let s = if sprinting {
**max_speed
} else {
**max_speed / config.sprint_movement_factor
2021-05-13 17:25:45 +00:00
};
**speed = s;
2021-05-26 21:46:20 +00:00
if let Some(strength) = strength {
2021-06-03 14:04:48 +00:00
direction *= strength;
2021-05-26 21:46:20 +00:00
}
2021-06-03 14:04:48 +00:00
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);
2021-05-13 17:25:45 +00:00
} else if destination.is_none() {
velocity.linvel = Vec2::ZERO.into();
**speed = 0.;
2021-05-13 17:25:45 +00:00
} else if sprinting {
**speed = **max_speed;
2021-05-13 17:25:45 +00:00
} else {
velocity.linvel = Vec2::ZERO.into();
**speed = **max_speed / 3.;
2021-05-13 17:25:45 +00:00
}
}
}
fn speak_direction(
mut tts: ResMut<Tts>,
mut cache: Local<HashMap<Entity, CardinalDirection>>,
player: Query<(Entity, &Player, &Transform), Changed<Transform>>,
) -> Result<(), Box<dyn Error>> {
if let Ok((entity, _, transform)) = player.single() {
let forward = transform.local_x();
let yaw = Angle::Radians(forward.y.atan2(forward.x));
if let Some(old_direction) = cache.get(&entity) {
let old_direction = *old_direction;
let direction: CardinalDirection = yaw.into();
if old_direction != direction {
let direction: String = direction.into();
tts.speak(direction, true)?;
2021-05-13 17:25:45 +00:00
}
cache.insert(entity, direction);
} else {
cache.insert(entity, yaw.into());
}
}
Ok(())
}
#[derive(Clone, Debug)]
2021-05-26 21:46:20 +00:00
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,
2021-05-13 17:25:45 +00:00
pub movement_states: Vec<S>,
pub movement_control_states: Vec<S>,
}
2021-05-26 21:46:20 +00:00
impl<S, A> Default for NavigationConfig<S, A> {
2021-05-13 17:25:45 +00:00
fn default() -> Self {
Self {
2021-05-26 21:46:20 +00:00
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.,
2021-05-13 17:25:45 +00:00
movement_states: vec![],
movement_control_states: vec![],
}
}
}
2021-05-26 22:30:03 +00:00
pub struct NavigationPlugin<'a, S, A>(PhantomData<&'a S>, PhantomData<&'a A>);
2021-05-13 17:25:45 +00:00
2021-05-26 21:46:20 +00:00
impl<'a, S, A> Default for NavigationPlugin<'a, S, A> {
2021-05-13 17:25:45 +00:00
fn default() -> Self {
2021-05-26 21:46:20 +00:00
Self(PhantomData, PhantomData)
2021-05-13 17:25:45 +00:00
}
}
2021-05-26 21:46:20 +00:00
impl<'a, S, A> Plugin for NavigationPlugin<'a, S, A>
2021-05-13 17:25:45 +00:00
where
S: bevy::ecs::component::Component + Clone + Debug + Eq + Hash,
2021-05-26 21:46:20 +00:00
A: Hash + Eq + Clone + Send + Sync,
2021-05-13 17:25:45 +00:00
'a: 'static,
{
fn build(&self, app: &mut AppBuilder) {
2021-05-26 21:46:20 +00:00
if !app.world().contains_resource::<NavigationConfig<S, A>>() {
app.insert_resource(NavigationConfig::<S, A>::default());
2021-05-13 17:25:45 +00:00
}
let config = app
.world()
2021-05-26 21:46:20 +00:00
.get_resource::<NavigationConfig<S, A>>()
2021-05-13 17:25:45 +00:00
.unwrap()
.clone();
app.register_type::<MaxSpeed>()
.register_type::<RotationSpeed>()
.register_type::<Sprinting>()
2021-06-02 22:02:38 +00:00
.add_system(speak_direction.system().chain(error_handler.system()));
2021-05-13 17:25:45 +00:00
if config.movement_states.is_empty() {
} else {
let states = config.movement_states;
2021-06-02 21:25:28 +00:00
for state in states {}
2021-05-13 17:25:45 +00:00
}
if config.movement_control_states.is_empty() {
2021-06-02 21:25:28 +00:00
app.add_system(movement_controls::<S, A>.system());
2021-05-13 17:25:45 +00:00
} else {
let states = config.movement_control_states;
for state in states {
app.add_system_set(
2021-06-02 21:25:28 +00:00
SystemSet::on_update(state).with_system(movement_controls::<S, A>.system()),
2021-05-13 17:25:45 +00:00
);
}
}
}
}