start to add physics

This commit is contained in:
Mitchell Marino 2024-11-02 23:29:48 -05:00
parent 9f9b7b03c7
commit 25c9c3681e
10 changed files with 4108 additions and 21 deletions

289
Cargo.lock generated
View File

@ -394,6 +394,36 @@ version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "avian3d"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "263f406c08c5ec296039ba06d7aa50e54f9ecd996f682aaa63eae25709e8935b"
dependencies = [
"avian_derive",
"bevy",
"bevy_math",
"bitflags 2.6.0",
"derive_more",
"fxhash",
"indexmap",
"itertools",
"nalgebra",
"parry3d",
"parry3d-f64",
]
[[package]]
name = "avian_derive"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4adeeecb6d4628d3ca11836ce9af8309f9552d4bd3e3f6e4368440d8163260c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.85",
]
[[package]]
name = "backtrace"
version = "0.3.74"
@ -1881,6 +1911,12 @@ dependencies = [
"const_soft_float",
]
[[package]]
name = "convert_case"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
[[package]]
name = "core-foundation"
version = "0.9.4"
@ -1996,6 +2032,7 @@ dependencies = [
name = "crooks"
version = "0.1.0"
dependencies = [
"avian3d",
"bevy",
"bevy_editor_pls",
"blenvy",
@ -2014,6 +2051,25 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.20"
@ -2107,6 +2163,19 @@ version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2"
[[package]]
name = "derive_more"
version = "0.99.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce"
dependencies = [
"convert_case",
"proc-macro2",
"quote",
"rustc_version",
"syn 2.0.85",
]
[[package]]
name = "dispatch"
version = "0.2.0"
@ -2545,6 +2614,15 @@ dependencies = [
"thread_local",
]
[[package]]
name = "fxhash"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c"
dependencies = [
"byteorder",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@ -3159,6 +3237,12 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "libm"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa"
[[package]]
name = "libredox"
version = "0.1.3"
@ -3188,6 +3272,7 @@ checksum = "dc3129ca879c52b7e814b7af6f7e1586c771a043ec90761e71d4322a65822848"
dependencies = [
"async-channel",
"async-compat",
"avian3d",
"bevy",
"bevy_web_keepalive",
"bincode",
@ -3286,6 +3371,16 @@ dependencies = [
"regex-automata 0.1.10",
]
[[package]]
name = "matrixmultiply"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9380b911e3e96d10c1f415da0876389aaf1b56759054eeb0de7df940c456ba1a"
dependencies = [
"autocfg",
"rawpointer",
]
[[package]]
name = "memchr"
version = "2.7.4"
@ -3380,6 +3475,34 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "nalgebra"
version = "0.32.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b5c17de023a86f59ed79891b2e5d5a94c705dbe904a5b5c9c952ea6221b03e4"
dependencies = [
"approx",
"glam 0.27.0",
"matrixmultiply",
"nalgebra-macros",
"num-complex",
"num-rational",
"num-traits",
"simba",
"typenum",
]
[[package]]
name = "nalgebra-macros"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "254a5372af8fc138e36684761d3c0cdb758a4410e938babcff1c860ce14ddbfc"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.85",
]
[[package]]
name = "ndk"
version = "0.8.0"
@ -3507,6 +3630,15 @@ dependencies = [
"winapi",
]
[[package]]
name = "num-complex"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
]
[[package]]
name = "num-derive"
version = "0.4.2"
@ -3518,6 +3650,25 @@ dependencies = [
"syn 2.0.85",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@ -3525,6 +3676,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
"libm",
]
[[package]]
@ -3877,6 +4029,52 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "parry3d"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa342e0cdfc774fed0196714290ba2d85408b8ce9f295c40a0b1e05f3f8256ab"
dependencies = [
"approx",
"arrayvec",
"bitflags 1.3.2",
"downcast-rs",
"either",
"log",
"nalgebra",
"num-derive",
"num-traits",
"rayon",
"rustc-hash",
"simba",
"slab",
"smallvec",
"spade",
]
[[package]]
name = "parry3d-f64"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdc07fa374273eca29066d59d3ded520bf845ed582e38c0d60109459ea4ed76e"
dependencies = [
"approx",
"arrayvec",
"bitflags 1.3.2",
"downcast-rs",
"either",
"log",
"nalgebra",
"num-derive",
"num-traits",
"rayon",
"rustc-hash",
"simba",
"slab",
"smallvec",
"spade",
]
[[package]]
name = "paste"
version = "1.0.15"
@ -4163,6 +4361,32 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
[[package]]
name = "rawpointer"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
[[package]]
name = "rayon"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2"
dependencies = [
"crossbeam-deque",
"crossbeam-utils",
]
[[package]]
name = "rectangle-pack"
version = "0.4.2"
@ -4243,6 +4467,12 @@ version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3df6368f71f205ff9c33c076d170dd56ebf68e8161c733c0caa07a7a5509ed53"
[[package]]
name = "robust"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cbf4a6aa5f6d6888f39e980649f3ad6b666acdce1d78e95b8a2cb076e687ae30"
[[package]]
name = "rodio"
version = "0.18.1"
@ -4278,6 +4508,15 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "0.38.38"
@ -4306,6 +4545,15 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
[[package]]
name = "safe_arch"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3460605018fdc9612bce72735cba0d27efbcd9904780d44c7e3a9948f96148a"
dependencies = [
"bytemuck",
]
[[package]]
name = "same-file"
version = "1.0.6"
@ -4352,6 +4600,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d369a96f978623eb3dc28807c4852d6cc617fed53da5d3c400feff1ef34a714a"
[[package]]
name = "semver"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b"
[[package]]
name = "send_wrapper"
version = "0.6.0"
@ -4405,6 +4659,19 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "simba"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "061507c94fc6ab4ba1c9a0305018408e312e17c041eb63bef8aa726fa33aceae"
dependencies = [
"approx",
"num-complex",
"num-traits",
"paste",
"wide",
]
[[package]]
name = "simd-adler32"
version = "0.3.7"
@ -4472,6 +4739,18 @@ dependencies = [
"serde",
]
[[package]]
name = "spade"
version = "2.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93f5ef1f863aca7d1d7dda7ccfc36a0a4279bd6d3c375176e5e0712e25cb4889"
dependencies = [
"hashbrown 0.14.5",
"num-traits",
"robust",
"smallvec",
]
[[package]]
name = "spinning_top"
version = "0.3.0"
@ -5284,6 +5563,16 @@ dependencies = [
"web-sys",
]
[[package]]
name = "wide"
version = "0.7.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b828f995bf1e9622031f8009f8481a85406ce1f4d4588ff746d872043e855690"
dependencies = [
"bytemuck",
"safe_arch",
]
[[package]]
name = "widestring"
version = "1.1.0"

View File

@ -4,12 +4,13 @@ version = "0.1.0"
edition = "2021"
[dependencies]
avian3d = "0.1.2"
bevy = { version = "0.14.2", features = ["jpeg"] }
bevy_editor_pls = "0.10.0"
blenvy = "0.1.0-alpha.1"
clap = { version = "4.5.20", features = ["derive"] }
lazy_static = "1.5.0"
lightyear = "0.17.1"
lightyear = { version = "0.17.1", features = ["avian3d"] }
serde = { version = "1.0.213", features = ["derive"] }
[profile.dev.package."*"]

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -2,9 +2,9 @@
assets:
[
("Player", File ( path: "blueprints/Player.glb" )),
("head.001", File ( path: "materials/head.001.glb" )),
("glasses.001", File ( path: "materials/glasses.001.glb" )),
("body.001", File ( path: "materials/body.001.glb" )),
("head.001", File ( path: "materials/head.001.glb" )),
("Hotel", File ( path: "blueprints/Hotel.glb" )),
("floor", File ( path: "materials/floor.glb" )),
]

File diff suppressed because it is too large Load Diff

450
src/char_controller.rs Normal file
View File

@ -0,0 +1,450 @@
use avian3d::{math::*, prelude::*};
use bevy::{ecs::query::Has, prelude::*, window::PrimaryWindow};
pub struct CharacterControllerPlugin;
impl Plugin for CharacterControllerPlugin {
fn build(&self, app: &mut App) {
app.add_event::<MovementAction>()
.add_systems(
Update,
(
(keyboard_input, cursor_input),
update_grounded,
apply_gravity,
movement,
apply_movement_damping,
)
.chain(),
)
.add_systems(
// Run collision handling after collision detection.
//
// NOTE: The collision implementation here is very basic and a bit buggy.
// A collide-and-slide algorithm would likely work better.
PostProcessCollisions,
kinematic_controller_collisions,
);
}
}
/// An event sent for a movement input action.
#[derive(Event)]
pub enum MovementAction {
Move(Vector2),
Rotate(Vec2),
Jump,
}
/// A marker component indicating that an entity is using a character controller.
#[derive(Component)]
pub struct CharacterController;
/// A marker component indicating that an entity is on the ground.
#[derive(Component)]
#[component(storage = "SparseSet")]
pub struct Grounded;
/// The acceleration used for character movement.
#[derive(Component)]
pub struct MovementAcceleration(Scalar);
/// The damping factor used for slowing down movement.
#[derive(Component)]
pub struct MovementDampingFactor(Scalar);
/// The strength of a jump.
#[derive(Component)]
pub struct JumpImpulse(Scalar);
/// The gravitational acceleration used for a character controller.
#[derive(Component)]
pub struct ControllerGravity(Vector);
/// The maximum angle a slope can have for a character controller
/// to be able to climb and jump. If the slope is steeper than this angle,
/// the character will slide down.
#[derive(Component)]
pub struct MaxSlopeAngle(Scalar);
/// A bundle that contains the components needed for a basic
/// kinematic character controller.
#[derive(Bundle)]
pub struct CharacterControllerBundle {
character_controller: CharacterController,
rigid_body: RigidBody,
collider: Collider,
ground_caster: ShapeCaster,
gravity: ControllerGravity,
movement: MovementBundle,
}
/// A bundle that contains components for character movement.
#[derive(Bundle)]
pub struct MovementBundle {
acceleration: MovementAcceleration,
damping: MovementDampingFactor,
jump_impulse: JumpImpulse,
max_slope_angle: MaxSlopeAngle,
}
impl MovementBundle {
pub const fn new(
acceleration: Scalar,
damping: Scalar,
jump_impulse: Scalar,
max_slope_angle: Scalar,
) -> Self {
Self {
acceleration: MovementAcceleration(acceleration),
damping: MovementDampingFactor(damping),
jump_impulse: JumpImpulse(jump_impulse),
max_slope_angle: MaxSlopeAngle(max_slope_angle),
}
}
}
impl Default for MovementBundle {
fn default() -> Self {
Self::new(30.0, 0.9, 7.0, PI * 0.45)
}
}
impl CharacterControllerBundle {
pub fn new(collider: Collider, gravity: Vector) -> Self {
// Create shape caster as a slightly smaller version of collider
let mut caster_shape = collider.clone();
caster_shape.set_scale(Vector::ONE * 0.99, 10);
Self {
character_controller: CharacterController,
rigid_body: RigidBody::Kinematic,
collider,
ground_caster: ShapeCaster::new(
caster_shape,
Vector::ZERO,
Quaternion::default(),
Dir3::NEG_Y,
)
.with_max_time_of_impact(0.2),
gravity: ControllerGravity(gravity),
movement: MovementBundle::default(),
}
}
pub fn with_movement(
mut self,
acceleration: Scalar,
damping: Scalar,
jump_impulse: Scalar,
max_slope_angle: Scalar,
) -> Self {
self.movement = MovementBundle::new(acceleration, damping, jump_impulse, max_slope_angle);
self
}
}
fn cursor_input(
mut q_windows: Query<&mut Window, With<PrimaryWindow>>,
mut ew_movement: EventWriter<MovementAction>,
) {
let mut window = q_windows.single_mut();
let window_center = window.size() / 2.;
if let Some(cursor_pos) = window.cursor_position() {
let delta = cursor_pos - window_center;
if delta != Vec2::ZERO {
ew_movement.send(MovementAction::Rotate(delta));
window.set_cursor_position(Some(window_center));
}
}
}
/// Sends [`MovementAction`] events based on keyboard input.
fn keyboard_input(
mut ew_movement: EventWriter<MovementAction>,
keyboard_input: Res<ButtonInput<KeyCode>>,
) {
let up = keyboard_input.any_pressed([KeyCode::KeyW, KeyCode::ArrowUp]);
let down = keyboard_input.any_pressed([KeyCode::KeyS, KeyCode::ArrowDown]);
let left = keyboard_input.any_pressed([KeyCode::KeyA, KeyCode::ArrowLeft]);
let right = keyboard_input.any_pressed([KeyCode::KeyD, KeyCode::ArrowRight]);
let horizontal = right as i8 - left as i8;
let vertical = up as i8 - down as i8;
let direction = Vector2::new(horizontal as Scalar, vertical as Scalar).clamp_length_max(1.0);
if direction != Vector2::ZERO {
ew_movement.send(MovementAction::Move(direction));
}
if keyboard_input.just_pressed(KeyCode::Space) {
ew_movement.send(MovementAction::Jump);
}
}
/// Updates the [`Grounded`] status for character controllers.
fn update_grounded(
mut commands: Commands,
mut query: Query<
(Entity, &ShapeHits, &Rotation, Option<&MaxSlopeAngle>),
With<CharacterController>,
>,
) {
for (entity, hits, rotation, max_slope_angle) in &mut query {
// The character is grounded if the shape caster has a hit with a normal
// that isn't too steep.
let is_grounded = hits.iter().any(|hit| {
if let Some(angle) = max_slope_angle {
(rotation * -hit.normal2).angle_between(Vector::Y).abs() <= angle.0
} else {
true
}
});
if is_grounded {
commands.entity(entity).insert(Grounded);
} else {
commands.entity(entity).remove::<Grounded>();
}
}
}
/// Responds to [`MovementAction`] events and moves character controllers accordingly.
fn movement(
time: Res<Time>,
mut movement_event_reader: EventReader<MovementAction>,
mut controllers: Query<(
&mut Transform,
&MovementAcceleration,
&JumpImpulse,
&mut LinearVelocity,
Has<Grounded>,
)>,
) {
// Precision is adjusted so that the example works with
// both the `f32` and `f64` features. Otherwise you don't need this.
let delta_time = time.delta_seconds_f64().adjust_precision();
for event in movement_event_reader.read() {
for (
mut transform,
movement_acceleration,
jump_impulse,
mut linear_velocity,
is_grounded,
) in &mut controllers
{
match event {
MovementAction::Move(direction) => {
let local_direction =
transform.rotation * Vec3::new(direction.y, 0., direction.x);
let local_direction = Vec2::new(local_direction.z, local_direction.x);
println!("{local_direction:?}");
linear_velocity.x +=
local_direction.x * movement_acceleration.0 * delta_time * 10.;
linear_velocity.z -=
local_direction.y * movement_acceleration.0 * delta_time * 10.;
}
MovementAction::Rotate(rot) => {
// TODO: un hard code the sensitityv
transform.rotate_y(rot.x * -0.001);
// TODO: Move head
}
MovementAction::Jump => {
if is_grounded {
linear_velocity.y = jump_impulse.0;
}
}
}
}
}
}
/// Applies [`ControllerGravity`] to character controllers.
fn apply_gravity(
time: Res<Time>,
mut controllers: Query<(&ControllerGravity, &mut LinearVelocity)>,
) {
// Precision is adjusted so that the example works with
// both the `f32` and `f64` features. Otherwise you don't need this.
let delta_time = time.delta_seconds_f64().adjust_precision();
for (gravity, mut linear_velocity) in &mut controllers {
linear_velocity.0 += gravity.0 * delta_time;
}
}
/// Slows down movement in the XZ plane.
fn apply_movement_damping(mut query: Query<(&MovementDampingFactor, &mut LinearVelocity)>) {
for (damping_factor, mut linear_velocity) in &mut query {
// We could use `LinearDamping`, but we don't want to dampen movement along the Y axis
linear_velocity.x *= damping_factor.0;
linear_velocity.z *= damping_factor.0;
}
}
/// Kinematic bodies do not get pushed by collisions by default,
/// so it needs to be done manually.
///
/// This system handles collision response for kinematic character controllers
/// by pushing them along their contact normals by the current penetration depth,
/// and applying velocity corrections in order to snap to slopes, slide along walls,
/// and predict collisions using speculative contacts.
#[allow(clippy::type_complexity)]
fn kinematic_controller_collisions(
collisions: Res<Collisions>,
bodies: Query<&RigidBody>,
collider_parents: Query<&ColliderParent, Without<Sensor>>,
mut character_controllers: Query<
(
&mut Position,
&Rotation,
&mut LinearVelocity,
Option<&MaxSlopeAngle>,
),
(With<RigidBody>, With<CharacterController>),
>,
time: Res<Time>,
) {
// Iterate through collisions and move the kinematic body to resolve penetration
for contacts in collisions.iter() {
// Get the rigid body entities of the colliders (colliders could be children)
let Ok([collider_parent1, collider_parent2]) =
collider_parents.get_many([contacts.entity1, contacts.entity2])
else {
continue;
};
// Get the body of the character controller and whether it is the first
// or second entity in the collision.
let is_first: bool;
let character_rb: RigidBody;
let is_other_dynamic: bool;
let (mut position, rotation, mut linear_velocity, max_slope_angle) =
if let Ok(character) = character_controllers.get_mut(collider_parent1.get()) {
is_first = true;
character_rb = *bodies.get(collider_parent1.get()).unwrap();
is_other_dynamic = bodies
.get(collider_parent2.get())
.is_ok_and(|rb| rb.is_dynamic());
character
} else if let Ok(character) = character_controllers.get_mut(collider_parent2.get()) {
is_first = false;
character_rb = *bodies.get(collider_parent2.get()).unwrap();
is_other_dynamic = bodies
.get(collider_parent1.get())
.is_ok_and(|rb| rb.is_dynamic());
character
} else {
continue;
};
// This system only handles collision response for kinematic character controllers.
if !character_rb.is_kinematic() {
continue;
}
// Iterate through contact manifolds and their contacts.
// Each contact in a single manifold shares the same contact normal.
for manifold in contacts.manifolds.iter() {
let normal = if is_first {
-manifold.global_normal1(rotation)
} else {
-manifold.global_normal2(rotation)
};
let mut deepest_penetration: Scalar = Scalar::MIN;
// Solve each penetrating contact in the manifold.
for contact in manifold.contacts.iter() {
if contact.penetration > 0.0 {
position.0 += normal * contact.penetration;
}
deepest_penetration = deepest_penetration.max(contact.penetration);
}
// For now, this system only handles velocity corrections for collisions against static geometry.
if is_other_dynamic {
continue;
}
// Determine if the slope is climbable or if it's too steep to walk on.
let slope_angle = normal.angle_between(Vector::Y);
let climbable = max_slope_angle.is_some_and(|angle| slope_angle.abs() <= angle.0);
if deepest_penetration > 0.0 {
// If the slope is climbable, snap the velocity so that the character
// up and down the surface smoothly.
if climbable {
// Points in the normal's direction in the XZ plane.
let normal_direction_xz =
normal.reject_from_normalized(Vector::Y).normalize_or_zero();
// The movement speed along the direction above.
let linear_velocity_xz = linear_velocity.dot(normal_direction_xz);
// Snap the Y speed based on the speed at which the character is moving
// up or down the slope, and how steep the slope is.
//
// A 2D visualization of the slope, the contact normal, and the velocity components:
//
//
// normal
// *
// │ * velocity_x
// │ * - - - - - -
// │ * | velocity_y
// │ * |
// *───────────────────*
let max_y_speed = -linear_velocity_xz * slope_angle.tan();
linear_velocity.y = linear_velocity.y.max(max_y_speed);
} else {
// The character is intersecting an unclimbable object, like a wall.
// We want the character to slide along the surface, similarly to
// a collide-and-slide algorithm.
// Don't apply an impulse if the character is moving away from the surface.
if linear_velocity.dot(normal) > 0.0 {
continue;
}
// Slide along the surface, rejecting the velocity along the contact normal.
let impulse = linear_velocity.reject_from_normalized(normal);
linear_velocity.0 = impulse;
}
} else {
// The character is not yet intersecting the other object,
// but the narrow phase detected a speculative collision.
//
// We need to push back the part of the velocity
// that would cause penetration within the next frame.
let normal_speed = linear_velocity.dot(normal);
// Don't apply an impulse if the character is moving away from the surface.
if normal_speed > 0.0 {
continue;
}
// Compute the impulse to apply.
let impulse_magnitude = normal_speed
- (deepest_penetration / time.delta_seconds_f64().adjust_precision());
let mut impulse = impulse_magnitude * normal;
// Apply the impulse differently depending on the slope angle.
if climbable {
// Avoid sliding down slopes.
linear_velocity.y -= impulse.y.min(0.0);
} else {
// Avoid climbing up walls.
impulse.y = impulse.y.max(0.0);
linear_velocity.0 -= impulse;
}
}
}
}
}

View File

@ -1,13 +1,16 @@
use avian3d::math::{Scalar, Vector};
use avian3d::prelude::*;
use bevy::log::LogPlugin;
use bevy::prelude::*;
use bevy::state::app::StatesPlugin;
use bevy_editor_pls::prelude::*;
use blenvy::{BlenvyPlugin, BlueprintInfo, GameWorldTag, HideUntilReady, SpawnBlueprint};
use char_controller::{CharacterControllerBundle, CharacterControllerPlugin};
use clap::Parser;
use lightyear::prelude::client::ClientPlugins;
use lightyear::prelude::server::ServerPlugins;
use std::f32::consts::PI;
mod char_controller;
pub mod protocol;
pub mod shared_net;
@ -48,20 +51,26 @@ pub struct Cli {
fn main() {
App::new()
.register_type::<Player>()
.insert_resource(Msaa::Sample4)
// .insert_resource(Msaa::Sample4)
.insert_resource(AmbientLight {
brightness: 200.0,
..default()
})
.add_plugins((
PhysicsPlugins::default(),
PhysicsDebugPlugin::default(),
CharacterControllerPlugin,
))
.add_plugins(ClientOrServerPlugin)
.add_plugins(protocol::ProtocolPlugin)
.add_plugins(EditorPlugin::default())
.add_plugins(BlenvyPlugin::default())
.add_systems(Startup, setup)
.add_systems(Update, setup_player)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
fn setup(mut commands: Commands) {
// commands.spawn(PointLightBundle {
// transform: Transform::from_translation(Vec3::Y * 30.),
// point_light: PointLight {
@ -73,22 +82,22 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// ..default()
// });
commands.spawn((
DirectionalLightBundle {
transform: Transform::from_translation(Vec3::Y * 10.).with_rotation(Quat::from_euler(
EulerRot::XYZ,
3. * PI / 2.,
0.,
0.,
)),
directional_light: DirectionalLight {
shadows_enabled: true,
..default()
},
..default()
},
Name::new("Sun"),
));
// commands.spawn((
// DirectionalLightBundle {
// transform: Transform::from_translation(Vec3::Y * 10.).with_rotation(Quat::from_euler(
// EulerRot::XYZ,
// 3. * PI / 2.,
// 0.,
// 0.,
// )),
// directional_light: DirectionalLight {
// shadows_enabled: true,
// ..default()
// },
// ..default()
// },
// Name::new("Sun"),
// ));
// commands.spawn(SceneBundle {
// scene: asset_server.load("hotel.glb#Scene0"),
@ -101,3 +110,20 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
GameWorldTag,
));
}
fn setup_player(
mut commands: Commands,
q_player: Query<Entity, (With<Player>, Without<Collider>)>,
) {
let Ok(player_entity) = q_player.get_single() else {
return;
};
commands.entity(player_entity).insert(
CharacterControllerBundle::new(
Collider::capsule_endpoints(1., Vec3::Y, Vec3::Y * 3.),
Vector::NEG_Y * 9.81 * 2.0,
)
.with_movement(30.0, 0.92, 7.0, (30.0 as Scalar).to_radians()),
);
}