Movement system and freelook system

This commit is contained in:
Franklin 2023-09-12 12:33:51 -04:00
parent c15592ec3f
commit c693d698a6
25 changed files with 287 additions and 104 deletions

View File

@ -1,5 +1,4 @@
use bevy::prelude::Component;
#[derive(Component)]
pub struct MainCamera;

View File

@ -1,14 +1,43 @@
use bevy::{prelude::*, window::CursorGrabMode};
use bevy_rapier3d::prelude::*;
use crate::logic::core::player::player_movement::{PlayerMovementInput, move_player, PlayerLinearYState};
use crate::logic::core::player::player_movement::{
move_player, PlayerLinearXZState, PlayerLinearYState, PlayerMovementInput,
};
use super::markers::player::Player;
/// System that captures input and fires events
pub fn capture_input(keyboard_input: Res<Input<KeyCode>>, query: Query<(&mut Velocity, &mut ExternalImpulse, &mut PlayerLinearYState, &Transform), With<Player>>, time: Res<Time>) {
pub fn capture_input(
keyboard_input: Res<Input<KeyCode>>,
player_query: Query<
(
&mut Velocity,
&mut ExternalImpulse,
&mut PlayerLinearYState,
&mut PlayerLinearXZState,
&Transform,
),
With<Player>,
>,
time: Res<Time>,
) {
// Don't allocate on each frame. Instead Check if any of the inputs are being pressed and then allocate.
if keyboard_input.any_pressed([KeyCode::A, KeyCode::S, KeyCode::D, KeyCode::W, KeyCode::C, KeyCode::Space]) {
if keyboard_input.any_pressed([
KeyCode::A,
KeyCode::S,
KeyCode::D,
KeyCode::W,
KeyCode::C,
KeyCode::Space,
]) || keyboard_input.any_just_released([
KeyCode::A,
KeyCode::S,
KeyCode::D,
KeyCode::W,
KeyCode::C,
KeyCode::Space,
]) {
let player_movement_input = PlayerMovementInput {
up: keyboard_input.just_pressed(KeyCode::Space),
down: keyboard_input.pressed(KeyCode::C),
@ -18,7 +47,7 @@ pub fn capture_input(keyboard_input: Res<Input<KeyCode>>, query: Query<(&mut Vel
back: keyboard_input.pressed(KeyCode::S),
sprint: keyboard_input.pressed(KeyCode::ShiftLeft),
};
move_player(player_movement_input, query, time);
move_player(player_movement_input, player_query, time);
}
}

View File

@ -1,7 +1,6 @@
pub const MAX_LINEAR_PLAYER_VELOCITY: f32 = 10.0;
pub const PLAYER_ACCELERATION: f32 = 12.0;
pub const PLAYER_JUMP_FORCE: f32 = 2500.0;
pub const PLAYER_JUMP_FORCE: f32 = 5000.0;
/// Time in ms that player must be grounded in order to jump again
pub const PLAYER_JUMP_COOLDOWN_MS: u128 = 75;
@ -9,3 +8,7 @@ pub const PLAYER_SPRINT_SPEED_MULTIPLIER: f32 = 2.0;
pub const PLAYER_CROUCH_SPEED_MULTIPLIER: f32 = 0.25;
pub const PLAYER_INITIAL_WEIGHT: f32 = 350.0;
pub const PLAYER_HEIGHT: f32 = 2.0;
pub const PLAYER_CAMERA_HEIGHT: f32 = 0.5;
pub const PLAYER_CROUCH_HEIGHT: f32 = 0.0;

View File

@ -0,0 +1 @@

View File

@ -1,7 +1,12 @@
use bevy::{prelude::*, input::mouse::MouseMotion};
use bevy::{input::mouse::MouseMotion, prelude::*};
//use bevy_rapier3d::prelude::*;
use crate::comps::core::{markers::player::Player, camera::MainCamera};
use crate::{
comps::core::{camera::MainCamera, markers::player::Player},
constants::player_values::{PLAYER_CAMERA_HEIGHT, PLAYER_CROUCH_HEIGHT},
};
use super::player_movement::PlayerLinearXZState;
/// Mouse sensitivity and movement speed
#[derive(Resource)]
@ -21,22 +26,24 @@ impl Default for MouseMovementSettings {
/// Synchronizes camera's translation & rotation (only 1 axis) to player.
pub fn sync_camera_to_player(
mut player: Query<&mut Transform, (With<Player>, Without<MainCamera>)>,
mut player: Query<(&mut Transform, &PlayerLinearXZState), (With<Player>, Without<MainCamera>)>,
mut camera: Query<&mut Transform, (With<MainCamera>, Without<Player>)>,
) {
let Ok(mut player) = player.get_single_mut() else { return };
let Ok((mut player, player_linear_xz_state)) = player.get_single_mut() else { return };
let Ok(mut camera_transform) = camera.get_single_mut() else { return };
camera_transform.translation = player.translation;
camera_transform.translation.y += 0.5;
if player_linear_xz_state.is_crouched() {
camera_transform.translation.y += PLAYER_CROUCH_HEIGHT;
} else {
camera_transform.translation.y += PLAYER_CAMERA_HEIGHT;
}
player.rotation = camera_transform.rotation;
//camera_transform.rotate_x(radians_from_degrees(-15.0)); // Make camera slightly point downward.
}
/// Handles looking around if cursor is locked
pub fn follow_cursor_with_camera(
settings: Res<MouseMovementSettings>,
@ -55,7 +62,8 @@ pub fn follow_cursor_with_camera(
}
pitch = pitch.clamp(-1.54, 1.54);
let desired_rotation_quat = Quat::from_axis_angle(Vec3::Y, yaw) * Quat::from_axis_angle(Vec3::X, pitch);
let desired_rotation_quat =
Quat::from_axis_angle(Vec3::Y, yaw) * Quat::from_axis_angle(Vec3::X, pitch);
for mut camera_transform in camera_query.iter_mut() {
camera_transform.rotation = desired_rotation_quat;

View File

@ -1,5 +1,5 @@
pub mod player_movement;
pub mod spawn_player;
pub mod camera_player_sync;
pub mod player_vertical_sync;
pub mod camera_effects;
pub mod camera_player_sync;
pub mod player_movement;
pub mod player_vertical_sync;
pub mod spawn_player;

View File

@ -1,35 +1,57 @@
use bevy::prelude::*;
use bevy_rapier3d::prelude::*;
use crate::{comps::core::markers::player::Player, constants::player_values::{MAX_LINEAR_PLAYER_VELOCITY, PLAYER_ACCELERATION, PLAYER_JUMP_COOLDOWN_MS, PLAYER_JUMP_FORCE, PLAYER_CROUCH_SPEED_MULTIPLIER, PLAYER_SPRINT_SPEED_MULTIPLIER}};
use crate::{
comps::core::markers::player::Player,
constants::player_values::{
MAX_LINEAR_PLAYER_VELOCITY, PLAYER_ACCELERATION, PLAYER_CROUCH_SPEED_MULTIPLIER,
PLAYER_JUMP_COOLDOWN_MS, PLAYER_JUMP_FORCE, PLAYER_SPRINT_SPEED_MULTIPLIER,
},
};
#[derive(Component)]
#[derive(Component, Debug)]
pub enum PlayerLinearYState {
Grounded(u128),
Jumping,
Falling
Falling,
}
#[allow(unused)]
impl PlayerLinearYState {
pub fn is_grounded(&self, longer_than: &u128) -> bool {
match self {
Self::Grounded(time_grounded) => {
time_grounded > longer_than
},
_ => false
Self::Grounded(time_grounded) => time_grounded > longer_than,
_ => false,
}
}
pub fn is_jumping(&self) -> bool {
match self {
Self::Jumping => true,
_ => false
_ => false,
}
}
pub fn is_falling(&self) -> bool {
match self {
Self::Falling => true,
_ => false
_ => false,
}
}
}
#[derive(Component, Default, Debug)]
pub enum PlayerLinearXZState {
Crouched,
Walking,
#[default]
Stopped,
Sprinting,
}
impl PlayerLinearXZState {
pub fn is_crouched(&self) -> bool {
match self {
Self::Crouched => true,
_ => false,
}
}
}
@ -56,9 +78,31 @@ pub struct PlayerMovementInput {
}
/// Applies game logic to determine how player should move.
pub fn move_player(player_movement_input: PlayerMovementInput, mut query: Query<(&mut Velocity, &mut ExternalImpulse, &mut PlayerLinearYState, &Transform), With<Player>>, time: Res<Time>,) {
for (mut player_velocity, mut player_external_force, mut player_linear_y_state, player_transform) in &mut query {
pub fn move_player(
player_movement_input: PlayerMovementInput,
mut query: Query<
(
&mut Velocity,
&mut ExternalImpulse,
&mut PlayerLinearYState,
&mut PlayerLinearXZState,
&Transform,
),
With<Player>,
>,
time: Res<Time>,
) {
for (
mut player_velocity,
mut player_external_force,
mut player_linear_y_state,
mut player_linear_xz_state,
player_transform,
) in &mut query
{
println!("{:?}", player_linear_xz_state);
let crouch_multiplier = if player_movement_input.down {
*player_linear_xz_state = PlayerLinearXZState::Crouched;
PLAYER_CROUCH_SPEED_MULTIPLIER
} else {
1.0
@ -71,18 +115,61 @@ pub fn move_player(player_movement_input: PlayerMovementInput, mut query: Query<
let local_z = player_transform.local_z();
let forward = -Vec3::new(local_z.x, 0.0, local_z.z);
let right = Vec3::new(local_z.z, 0.0, -local_z.x);
if !player_linear_y_state.is_jumping() && !player_linear_y_state.is_falling() { // Only let player move when grounded
if !player_linear_y_state.is_jumping() && !player_linear_y_state.is_falling() {
// Only let player move when grounded
if player_movement_input.front {
player_velocity.linvel = apply_movement_acceleration_to_vec(forward, player_velocity.linvel, time.delta_seconds(), sprint_multiplier);
if sprint_multiplier == PLAYER_SPRINT_SPEED_MULTIPLIER {
*player_linear_xz_state = PlayerLinearXZState::Sprinting;
} else if crouch_multiplier == PLAYER_CROUCH_SPEED_MULTIPLIER {
*player_linear_xz_state = PlayerLinearXZState::Crouched;
} else {
*player_linear_xz_state = PlayerLinearXZState::Walking;
}
player_velocity.linvel = apply_movement_acceleration_to_vec(
forward,
player_velocity.linvel,
time.delta_seconds(),
sprint_multiplier,
);
}
if player_movement_input.back {
player_velocity.linvel = apply_movement_acceleration_to_vec(-forward, player_velocity.linvel, time.delta_seconds(), 1.0);
if crouch_multiplier == PLAYER_CROUCH_SPEED_MULTIPLIER {
*player_linear_xz_state = PlayerLinearXZState::Crouched;
} else {
*player_linear_xz_state = PlayerLinearXZState::Walking;
}
player_velocity.linvel = apply_movement_acceleration_to_vec(
-forward,
player_velocity.linvel,
time.delta_seconds(),
1.0,
);
}
if player_movement_input.right {
player_velocity.linvel = apply_movement_acceleration_to_vec(right, player_velocity.linvel, time.delta_seconds(), 1.0);
if crouch_multiplier == PLAYER_CROUCH_SPEED_MULTIPLIER {
*player_linear_xz_state = PlayerLinearXZState::Crouched;
} else {
*player_linear_xz_state = PlayerLinearXZState::Walking;
}
player_velocity.linvel = apply_movement_acceleration_to_vec(
right,
player_velocity.linvel,
time.delta_seconds(),
1.0,
);
}
if player_movement_input.left {
player_velocity.linvel = apply_movement_acceleration_to_vec(-right, player_velocity.linvel, time.delta_seconds(), 1.0);
if crouch_multiplier == PLAYER_CROUCH_SPEED_MULTIPLIER {
*player_linear_xz_state = PlayerLinearXZState::Crouched;
} else {
*player_linear_xz_state = PlayerLinearXZState::Walking;
}
player_velocity.linvel = apply_movement_acceleration_to_vec(
-right,
player_velocity.linvel,
time.delta_seconds(),
1.0,
);
}
}
@ -91,23 +178,44 @@ pub fn move_player(player_movement_input: PlayerMovementInput, mut query: Query<
*player_linear_y_state = PlayerLinearYState::Jumping;
}
// When player velocity exceeds max linear velocity then set to max_linear_vel value
if player_velocity.linvel.x.abs() > MAX_LINEAR_PLAYER_VELOCITY * crouch_multiplier * sprint_multiplier {
if player_velocity.linvel.x.abs()
> MAX_LINEAR_PLAYER_VELOCITY * crouch_multiplier * sprint_multiplier
{
let positive = player_velocity.linvel.x.is_sign_positive();
if positive { player_velocity.linvel.x = MAX_LINEAR_PLAYER_VELOCITY * crouch_multiplier * sprint_multiplier }
else { player_velocity.linvel.x = MAX_LINEAR_PLAYER_VELOCITY * -1.0 * crouch_multiplier }
if positive {
player_velocity.linvel.x =
MAX_LINEAR_PLAYER_VELOCITY * crouch_multiplier * sprint_multiplier
} else {
player_velocity.linvel.x = MAX_LINEAR_PLAYER_VELOCITY * -1.0 * crouch_multiplier
}
if player_velocity.linvel.z.abs() > MAX_LINEAR_PLAYER_VELOCITY * crouch_multiplier * sprint_multiplier{
}
if player_velocity.linvel.z.abs()
> MAX_LINEAR_PLAYER_VELOCITY * crouch_multiplier * sprint_multiplier
{
let positive = player_velocity.linvel.z.is_sign_positive();
if positive { player_velocity.linvel.z = MAX_LINEAR_PLAYER_VELOCITY * crouch_multiplier }
else { player_velocity.linvel.z = MAX_LINEAR_PLAYER_VELOCITY * -1.0 * crouch_multiplier }
if positive {
player_velocity.linvel.z = MAX_LINEAR_PLAYER_VELOCITY * crouch_multiplier
} else {
player_velocity.linvel.z = MAX_LINEAR_PLAYER_VELOCITY * -1.0 * crouch_multiplier
}
}
if player_velocity.linvel.x > -1.0
&& player_velocity.linvel.x < 1.0
&& player_velocity.linvel.z > -1.0
&& player_velocity.linvel.z < 1.0
&& !player_movement_input.down
{
*player_linear_xz_state = PlayerLinearXZState::Stopped;
}
}
}
// currentLinearVelocity + Acceleration * deltaTime
fn apply_movement_acceleration_to_vec(direction: Vec3, current_linvel: Vec3, delta_time_secs: f32, multiplier: f32) -> Vec3 {
current_linvel + (
direction * PLAYER_ACCELERATION * delta_time_secs * multiplier
)
fn apply_movement_acceleration_to_vec(
direction: Vec3,
current_linvel: Vec3,
delta_time_secs: f32,
multiplier: f32,
) -> Vec3 {
current_linvel + (direction * PLAYER_ACCELERATION * delta_time_secs * multiplier)
}

View File

@ -5,20 +5,21 @@ use crate::comps::core::markers::player::Player;
use super::player_movement::PlayerLinearYState;
/// System that captures linear y velocity and determines whether player is falling or grounded, and how long the player has been grounded for.
pub fn sync_player_y_state(mut query: Query<(&Velocity, &mut PlayerLinearYState), With<Player>>, time: Res<Time>) {
pub fn sync_player_y_state(
mut query: Query<(&Velocity, &mut PlayerLinearYState), With<Player>>,
time: Res<Time>,
) {
for (player_velocity, mut player_linear_y_state) in &mut query {
if player_velocity.linvel.y < -1.0 {
*player_linear_y_state = PlayerLinearYState::Falling;
} else if player_velocity.linvel.y >= -1.0 && player_velocity.linvel.y <= 1.0 {
let previous_grounded_time = match *player_linear_y_state {
PlayerLinearYState::Grounded(grounded_for) => grounded_for,
_ => 0
_ => 0,
};
*player_linear_y_state = PlayerLinearYState::Grounded(previous_grounded_time + time.delta().as_millis());
*player_linear_y_state =
PlayerLinearYState::Grounded(previous_grounded_time + time.delta().as_millis());
}
}
}

View File

@ -1,31 +1,47 @@
use bevy::prelude::*;
use bevy_rapier3d::prelude::*;
use crate::{comps::core::{markers::player::Player, camera::MainCamera}, constants::player_values::PLAYER_INITIAL_WEIGHT};
use crate::{
comps::core::{camera::MainCamera, markers::player::Player},
constants::player_values::{PLAYER_HEIGHT, PLAYER_INITIAL_WEIGHT},
};
use super::player_movement::PlayerLinearYState;
use super::player_movement::{PlayerLinearXZState, PlayerLinearYState};
pub fn spawn_player(mut commands: Commands) {
commands.spawn(Player)
commands
.spawn(Player)
.insert(RigidBody::Dynamic)
.insert(GravityScale(2.0))
.insert(Collider::capsule_y(2.0, 2.0))
.insert(Collider::capsule_y(PLAYER_HEIGHT, 2.0))
.insert(Restitution::coefficient(0.0))
.insert(Friction { coefficient: 0.0, ..Default::default() })
.insert(TransformBundle{ local: Transform::from_xyz(3.0, 5.0, 2.0), global: Default::default() })
.insert(Friction {
coefficient: 0.0,
..Default::default()
})
.insert(TransformBundle {
local: Transform::from_xyz(3.0, 5.0, 2.0),
global: Default::default(),
})
.insert(Velocity::zero())
.insert(Damping { linear_damping: 1.0, angular_damping: 1.0 })
.insert(LockedAxes::ROTATION_LOCKED_Z | LockedAxes::ROTATION_LOCKED_X | LockedAxes::ROTATION_LOCKED_Y)
.insert(Damping {
linear_damping: 1.0,
angular_damping: 1.0,
})
.insert(
LockedAxes::ROTATION_LOCKED_Z
| LockedAxes::ROTATION_LOCKED_X
| LockedAxes::ROTATION_LOCKED_Y,
)
.insert(ColliderMassProperties::Mass(PLAYER_INITIAL_WEIGHT))
.insert(ExternalImpulse {
impulse: Vec3::ZERO,
torque_impulse: Vec3::ZERO,
})
.insert(PlayerLinearYState::Falling);
.insert(PlayerLinearYState::Falling)
.insert(PlayerLinearXZState::Stopped);
commands.spawn(MainCamera)
.insert(Camera3dBundle {
commands.spawn(MainCamera).insert(Camera3dBundle {
transform: Transform::from_xyz(0.0, 0.0, 0.0).looking_at(Vec3::ZERO, Vec3::Y),
..Default::default()
});

View File

@ -4,10 +4,10 @@ use scenes::scene1;
mod assets;
mod comps;
mod constants;
mod logic;
mod scenes;
mod setup;
mod logic;
mod constants;
mod utils;
fn main() {

View File

@ -1,8 +1,11 @@
use bevy::prelude::*;
use bevy_rapier3d::prelude::*;
pub fn spawn_ground(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,) {
pub fn spawn_ground(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands
.spawn(Collider::cuboid(20.0, 0.1, 20.0))
.insert(TransformBundle::from(Transform::from_xyz(0.0, -2.0, 0.0)))

View File

@ -1,10 +1,18 @@
use bevy::prelude::*;
use crate::{logic::core::player::{spawn_player::spawn_player, camera_player_sync::{sync_camera_to_player, MouseMovementSettings, follow_cursor_with_camera}, player_vertical_sync::sync_player_y_state}, comps::core::controller::{capture_input, capture_cursor}};
use crate::{
comps::core::controller::{capture_cursor, capture_input},
logic::core::player::{
camera_player_sync::{
follow_cursor_with_camera, sync_camera_to_player, MouseMovementSettings,
},
player_vertical_sync::sync_player_y_state,
spawn_player::spawn_player,
},
};
use super::{ground::spawn_ground, lighting::setup_lighting, obstacles::spawn_obstacles};
pub fn load_scene(application: &mut App) {
application.insert_resource(MouseMovementSettings::default());
// Startup
@ -12,7 +20,6 @@ pub fn load_scene(application: &mut App) {
application.add_systems(Startup, spawn_obstacles);
application.add_systems(Startup, spawn_player);
// Update
application.add_systems(Update, capture_input);
application.add_systems(Update, sync_camera_to_player);

View File

@ -2,7 +2,13 @@ use bevy::prelude::*;
pub fn setup_lighting(mut commands: Commands) {
commands.spawn(SpotLightBundle {
spot_light: SpotLight { color: Color::WHITE, intensity: 3000.0, range: 500.0, shadows_enabled: true, ..Default::default() },
spot_light: SpotLight {
color: Color::WHITE,
intensity: 3000.0,
range: 500.0,
shadows_enabled: true,
..Default::default()
},
transform: Transform::from_xyz(20.0, 20.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y),
visibility: Visibility::Visible,
..Default::default()

View File

@ -1,8 +1,11 @@
use bevy::prelude::*;
use bevy_rapier3d::prelude::*;
pub fn spawn_obstacles(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,) {
pub fn spawn_obstacles(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let box_1_mesh = shape::Box::new(3.0, 7.0, 3.0).into();
let box_2_mesh = shape::Box::new(3.0, 7.0, 3.0).into();
let box_3_mesh = shape::Box::new(3.0, 7.0, 3.0).into();

View File

@ -0,0 +1 @@

View File

@ -1,2 +1 @@
pub mod rad_deg;

View File

@ -1,6 +1,5 @@
use std::f32::consts::PI;
#[allow(unused)]
pub fn radians_from_degrees(degrees: f32) -> f32 {
(PI * degrees) / 180.0