Compare commits
No commits in common. "main" and "shapecast" have entirely different histories.
6 changed files with 1208 additions and 846 deletions
1590
Cargo.lock
generated
1590
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
@ -4,14 +4,12 @@ version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bevy = { version = "0.16", features = ["bevy_dev_tools", "configurable_error_handler"] }
|
bevy = { version = "0.15", features = ["bevy_dev_tools"] }
|
||||||
|
bevy-inspector-egui = "0.29"
|
||||||
|
|
||||||
[dependencies.avian3d]
|
[dependencies.avian3d]
|
||||||
default-features = false
|
default-features = false
|
||||||
#version = "0.2"
|
version = "0.2"
|
||||||
git = "https://github.com/Jondolf/avian"
|
|
||||||
branch = "main"
|
|
||||||
features = ["3d", "f32", "parry-f32", "debug-plugin", "default-collider", "collider-from-mesh"]
|
features = ["3d", "f32", "parry-f32", "debug-plugin", "default-collider", "collider-from-mesh"]
|
||||||
|
|
||||||
|
|
||||||
|
|
247
src/bike.rs
247
src/bike.rs
|
@ -1,24 +1,12 @@
|
||||||
use avian3d::{
|
use avian3d::{
|
||||||
math::{Scalar, FRAC_PI_2},
|
math::{Scalar, FRAC_PI_2},
|
||||||
prelude::{
|
prelude::*,
|
||||||
AngularDamping, Collider, ColliderDensity, CollisionLayers, ExternalForce, ExternalTorque,
|
|
||||||
LinearDamping, RayCaster, RigidBody, SleepingDisabled, SpatialQueryFilter,
|
|
||||||
TransformInterpolation,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
use bevy::{
|
|
||||||
asset::Handle,
|
|
||||||
ecs::{bundle::Bundle, entity::Entity},
|
|
||||||
prelude::{
|
|
||||||
children, AlphaMode, App, Assets, Capsule3d, Color, Commands, Component, Dir3, Mesh,
|
|
||||||
Mesh3d, MeshMaterial3d, Name, Plugin, Reflect, ResMut, SpawnRelated, Sphere,
|
|
||||||
StandardMaterial, Startup, Transform, Vec3, Visibility,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
use crate::physics::CatControllerState;
|
use crate::physics::CatControllerState;
|
||||||
|
|
||||||
pub const SPRING_CONSTANT: Scalar = 40.0;
|
pub const SPRING_CONSTANT: Scalar = 60.0;
|
||||||
pub const DAMPING_CONSTANT: Scalar = 10.0;
|
pub const DAMPING_CONSTANT: Scalar = 10.0;
|
||||||
pub const WHEEL_RADIUS: Scalar = 0.4;
|
pub const WHEEL_RADIUS: Scalar = 0.4;
|
||||||
pub const REST_DISTANCE: Scalar = 1.5 + WHEEL_RADIUS;
|
pub const REST_DISTANCE: Scalar = 1.5 + WHEEL_RADIUS;
|
||||||
|
@ -36,6 +24,7 @@ pub enum CyberWheel {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Component, Clone, Copy, Debug, Reflect, Default)]
|
#[derive(Component, Clone, Copy, Debug, Reflect, Default)]
|
||||||
|
#[reflect(Component)]
|
||||||
pub struct WheelState {
|
pub struct WheelState {
|
||||||
pub displacement: Scalar,
|
pub displacement: Scalar,
|
||||||
pub force_normal: Scalar,
|
pub force_normal: Scalar,
|
||||||
|
@ -51,6 +40,7 @@ impl WheelState {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Component, Clone, Copy, Debug, Reflect)]
|
#[derive(Component, Clone, Copy, Debug, Reflect)]
|
||||||
|
#[reflect(Component)]
|
||||||
#[require(WheelState)]
|
#[require(WheelState)]
|
||||||
pub struct WheelConfig {
|
pub struct WheelConfig {
|
||||||
pub attach: Vec3,
|
pub attach: Vec3,
|
||||||
|
@ -92,113 +82,137 @@ fn spawn_bike(
|
||||||
let body_collider =
|
let body_collider =
|
||||||
Collider::capsule_endpoints(0.5, Vec3::new(0.0, 0.0, -0.65), Vec3::new(0.0, 0.0, 0.8));
|
Collider::capsule_endpoints(0.5, Vec3::new(0.0, 0.0, -0.65), Vec3::new(0.0, 0.0, 0.8));
|
||||||
|
|
||||||
let pbr_bundle = {
|
commands
|
||||||
let color = Color::srgb(0.7, 0.05, 0.7);
|
.spawn((xform, Visibility::default()))
|
||||||
let mut xform = Transform::default();
|
.insert((
|
||||||
xform.rotate_x(FRAC_PI_2);
|
Name::new("body"),
|
||||||
(
|
RigidBody::Dynamic,
|
||||||
Mesh3d(meshes.add(Capsule3d::new(0.5, 1.45))),
|
body_collider,
|
||||||
xform,
|
CollisionLayers::from_bits(1, 1),
|
||||||
Visibility::Visible,
|
SleepingDisabled,
|
||||||
MeshMaterial3d(materials.add(color)),
|
CyberBikeBody,
|
||||||
TransformInterpolation,
|
CatControllerState::default(),
|
||||||
)
|
ColliderDensity(1.2),
|
||||||
};
|
AngularDamping(0.2),
|
||||||
|
LinearDamping(0.1),
|
||||||
let mut body = commands.spawn((xform, Visibility::default()));
|
ExternalForce::ZERO.with_persistence(false),
|
||||||
body.insert((
|
ExternalTorque::ZERO.with_persistence(false),
|
||||||
Name::new("body"),
|
))
|
||||||
RigidBody::Dynamic,
|
.with_children(|builder| {
|
||||||
body_collider,
|
let color = Color::srgb(0.7, 0.05, 0.7);
|
||||||
CollisionLayers::from_bits(1, 1),
|
let mut xform = Transform::default();
|
||||||
SleepingDisabled,
|
xform.rotate_x(FRAC_PI_2);
|
||||||
CyberBikeBody,
|
let pbr_bundle = (
|
||||||
CatControllerState::default(),
|
Mesh3d(meshes.add(Capsule3d::new(0.5, 1.45))),
|
||||||
ColliderDensity(1.6),
|
xform,
|
||||||
AngularDamping(0.2),
|
MeshMaterial3d(materials.add(color)),
|
||||||
LinearDamping(0.1),
|
);
|
||||||
ExternalForce::ZERO.with_persistence(false),
|
builder.spawn(pbr_bundle);
|
||||||
ExternalTorque::ZERO.with_persistence(false),
|
spawn_wheels(builder, meshes, materials, builder.parent_entity());
|
||||||
));
|
});
|
||||||
|
|
||||||
body.insert(spawn_children(body.id(), meshes, materials))
|
|
||||||
.with_child(pbr_bundle);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn spawn_children(
|
fn spawn_wheels(
|
||||||
parent: Entity,
|
commands: &mut ChildBuilder,
|
||||||
mut meshes: ResMut<Assets<Mesh>>,
|
mut meshes: ResMut<Assets<Mesh>>,
|
||||||
mut materials: ResMut<Assets<StandardMaterial>>,
|
mut materials: ResMut<Assets<StandardMaterial>>,
|
||||||
) -> impl Bundle {
|
body: Entity,
|
||||||
|
) {
|
||||||
let mesh: Mesh = Sphere::new(WHEEL_RADIUS).into();
|
let mesh: Mesh = Sphere::new(WHEEL_RADIUS).into();
|
||||||
let wheel_material = StandardMaterial {
|
|
||||||
|
let front_rake = Vec3::new(0.0, -1.0, -0.9).normalize(); // about 30 degrees
|
||||||
|
let front_wheel_pos = FRONT_ATTACH + (front_rake * REST_DISTANCE);
|
||||||
|
|
||||||
|
wheel_caster(
|
||||||
|
commands,
|
||||||
|
FRONT_ATTACH,
|
||||||
|
Dir3::new_unchecked(front_rake),
|
||||||
|
body,
|
||||||
|
REST_DISTANCE,
|
||||||
|
CyberWheel::Front,
|
||||||
|
);
|
||||||
|
wheel_mesh(
|
||||||
|
commands,
|
||||||
|
&mut meshes,
|
||||||
|
&mut materials,
|
||||||
|
front_wheel_pos,
|
||||||
|
mesh.clone(),
|
||||||
|
WheelConfig::new(
|
||||||
|
FRONT_ATTACH,
|
||||||
|
REST_DISTANCE,
|
||||||
|
SPRING_CONSTANT,
|
||||||
|
DAMPING_CONSTANT,
|
||||||
|
FRICTION_COEFF,
|
||||||
|
WHEEL_RADIUS,
|
||||||
|
),
|
||||||
|
CyberWheel::Front,
|
||||||
|
);
|
||||||
|
|
||||||
|
let rear_rake = Vec3::new(0.0, -1.0, 0.9).normalize();
|
||||||
|
let rear_wheel_pos = REAR_ATTACH + (rear_rake * REST_DISTANCE);
|
||||||
|
|
||||||
|
wheel_caster(
|
||||||
|
commands,
|
||||||
|
REAR_ATTACH,
|
||||||
|
Dir3::new_unchecked(rear_rake),
|
||||||
|
body,
|
||||||
|
REST_DISTANCE,
|
||||||
|
CyberWheel::Rear,
|
||||||
|
);
|
||||||
|
wheel_mesh(
|
||||||
|
commands,
|
||||||
|
&mut meshes,
|
||||||
|
&mut materials,
|
||||||
|
rear_wheel_pos,
|
||||||
|
mesh,
|
||||||
|
WheelConfig::new(
|
||||||
|
REAR_ATTACH,
|
||||||
|
REST_DISTANCE,
|
||||||
|
SPRING_CONSTANT,
|
||||||
|
DAMPING_CONSTANT,
|
||||||
|
FRICTION_COEFF,
|
||||||
|
WHEEL_RADIUS,
|
||||||
|
),
|
||||||
|
CyberWheel::Rear,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
//-************************************************************************
|
||||||
|
// helper fns for the wheels
|
||||||
|
//-************************************************************************
|
||||||
|
|
||||||
|
fn wheel_caster(
|
||||||
|
commands: &mut ChildBuilder,
|
||||||
|
origin: Vec3,
|
||||||
|
direction: Dir3,
|
||||||
|
parent: Entity,
|
||||||
|
rest_dist: Scalar,
|
||||||
|
wheel: CyberWheel,
|
||||||
|
) {
|
||||||
|
let caster = RayCaster::new(origin, direction)
|
||||||
|
.with_max_distance(rest_dist)
|
||||||
|
.with_max_hits(1)
|
||||||
|
.with_query_filter(SpatialQueryFilter::from_excluded_entities([parent]));
|
||||||
|
|
||||||
|
commands.spawn((caster, wheel));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wheel_mesh(
|
||||||
|
commands: &mut ChildBuilder,
|
||||||
|
meshes: &mut ResMut<Assets<Mesh>>,
|
||||||
|
materials: &mut ResMut<Assets<StandardMaterial>>,
|
||||||
|
position: Vec3,
|
||||||
|
tire_mesh: Mesh,
|
||||||
|
config: WheelConfig,
|
||||||
|
wheel: CyberWheel,
|
||||||
|
) {
|
||||||
|
let wheel_material = &StandardMaterial {
|
||||||
base_color: Color::srgb(0.01, 0.01, 0.01),
|
base_color: Color::srgb(0.01, 0.01, 0.01),
|
||||||
alpha_mode: AlphaMode::Opaque,
|
alpha_mode: AlphaMode::Opaque,
|
||||||
perceptual_roughness: 0.5,
|
perceptual_roughness: 0.5,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
let mesh = meshes.add(mesh);
|
|
||||||
let material = materials.add(wheel_material);
|
|
||||||
|
|
||||||
let front_rake = Vec3::new(0.0, -1.0, -0.9).normalize(); // about 30 degrees
|
|
||||||
let front_wheel_pos = FRONT_ATTACH + (front_rake * REST_DISTANCE);
|
|
||||||
let rear_rake = Vec3::new(0.0, -1.0, 0.9).normalize();
|
|
||||||
let rear_wheel_pos = REAR_ATTACH + (rear_rake * REST_DISTANCE);
|
|
||||||
|
|
||||||
children![
|
|
||||||
(
|
|
||||||
RayCaster::new(FRONT_ATTACH, Dir3::new_unchecked(front_rake))
|
|
||||||
.with_max_hits(1)
|
|
||||||
.with_max_distance(REST_DISTANCE)
|
|
||||||
.with_query_filter(SpatialQueryFilter::from_excluded_entities([parent])),
|
|
||||||
CyberWheel::Front
|
|
||||||
),
|
|
||||||
wheel_bundle(
|
|
||||||
mesh.clone(),
|
|
||||||
material.clone(),
|
|
||||||
front_wheel_pos,
|
|
||||||
WheelConfig::new(
|
|
||||||
FRONT_ATTACH,
|
|
||||||
REST_DISTANCE,
|
|
||||||
SPRING_CONSTANT - 5.0,
|
|
||||||
DAMPING_CONSTANT,
|
|
||||||
FRICTION_COEFF,
|
|
||||||
WHEEL_RADIUS,
|
|
||||||
),
|
|
||||||
CyberWheel::Front,
|
|
||||||
),
|
|
||||||
(
|
|
||||||
RayCaster::new(REAR_ATTACH, Dir3::new_unchecked(rear_rake))
|
|
||||||
.with_max_hits(1)
|
|
||||||
.with_max_distance(REST_DISTANCE)
|
|
||||||
.with_query_filter(SpatialQueryFilter::from_excluded_entities([parent])),
|
|
||||||
CyberWheel::Rear,
|
|
||||||
),
|
|
||||||
wheel_bundle(
|
|
||||||
mesh,
|
|
||||||
material,
|
|
||||||
rear_wheel_pos,
|
|
||||||
WheelConfig::new(
|
|
||||||
REAR_ATTACH,
|
|
||||||
REST_DISTANCE,
|
|
||||||
SPRING_CONSTANT + 10.0,
|
|
||||||
DAMPING_CONSTANT,
|
|
||||||
FRICTION_COEFF,
|
|
||||||
WHEEL_RADIUS,
|
|
||||||
),
|
|
||||||
CyberWheel::Rear,
|
|
||||||
),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wheel_bundle(
|
|
||||||
mesh: Handle<Mesh>,
|
|
||||||
material: Handle<StandardMaterial>,
|
|
||||||
position: Vec3,
|
|
||||||
config: WheelConfig,
|
|
||||||
wheel: CyberWheel,
|
|
||||||
) -> impl Bundle {
|
|
||||||
let xform = Transform::from_translation(position);
|
let xform = Transform::from_translation(position);
|
||||||
|
|
||||||
let name = match wheel {
|
let name = match wheel {
|
||||||
|
@ -206,18 +220,15 @@ fn wheel_bundle(
|
||||||
CyberWheel::Rear => "rear tire",
|
CyberWheel::Rear => "rear tire",
|
||||||
};
|
};
|
||||||
|
|
||||||
(
|
commands.spawn((
|
||||||
Name::new(name),
|
Name::new(name),
|
||||||
config,
|
config,
|
||||||
Mesh3d(mesh),
|
Mesh3d(meshes.add(tire_mesh)),
|
||||||
MeshMaterial3d(material),
|
MeshMaterial3d(materials.add(wheel_material.clone())),
|
||||||
xform,
|
xform,
|
||||||
Collider::sphere(WHEEL_RADIUS),
|
|
||||||
ColliderDensity(0.5),
|
|
||||||
CollisionLayers::NONE,
|
|
||||||
TransformInterpolation,
|
TransformInterpolation,
|
||||||
wheel,
|
wheel,
|
||||||
)
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct CyberBikePlugin;
|
pub struct CyberBikePlugin;
|
||||||
|
|
|
@ -1,10 +1,4 @@
|
||||||
use bevy::{
|
use bevy::{prelude::*, utils::HashSet};
|
||||||
platform::collections::HashSet,
|
|
||||||
prelude::{
|
|
||||||
App, ButtonInput, Camera3d, Commands, Component, KeyCode, Plugin, Quat, Query, Res, ResMut,
|
|
||||||
Resource, Result, Startup, Transform, Update, Vec, Vec3, With, Without,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::bike::CyberBikeBody;
|
use crate::bike::CyberBikeBody;
|
||||||
|
|
||||||
|
@ -71,8 +65,8 @@ fn follow_bike(
|
||||||
mut camera: Query<&mut Transform, (With<CyberCameras>, Without<CyberBikeBody>)>,
|
mut camera: Query<&mut Transform, (With<CyberCameras>, Without<CyberBikeBody>)>,
|
||||||
bike: Query<&Transform, (With<CyberBikeBody>, Without<CyberCameras>)>,
|
bike: Query<&Transform, (With<CyberBikeBody>, Without<CyberCameras>)>,
|
||||||
offset: Res<DebugCamOffset>,
|
offset: Res<DebugCamOffset>,
|
||||||
) -> Result {
|
) {
|
||||||
let bike_xform = *bike.single()?;
|
let bike_xform = *bike.single();
|
||||||
let up = Vec3::Y;
|
let up = Vec3::Y;
|
||||||
|
|
||||||
let mut ncx = Transform::from_translation(bike_xform.translation);
|
let mut ncx = Transform::from_translation(bike_xform.translation);
|
||||||
|
@ -81,10 +75,8 @@ fn follow_bike(
|
||||||
ncx.translation += ncx.up() * offset.alt;
|
ncx.translation += ncx.up() * offset.alt;
|
||||||
ncx.look_at(bike_xform.translation, up);
|
ncx.look_at(bike_xform.translation, up);
|
||||||
|
|
||||||
let mut cam_xform = camera.single_mut()?;
|
let mut cam_xform = camera.single_mut();
|
||||||
*cam_xform = ncx;
|
*cam_xform = ncx;
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct CamPlug;
|
pub struct CamPlug;
|
||||||
|
|
44
src/main.rs
44
src/main.rs
|
@ -5,12 +5,13 @@ use bevy::{
|
||||||
color::{palettes::css::SILVER, Alpha},
|
color::{palettes::css::SILVER, Alpha},
|
||||||
pbr::MeshMaterial3d,
|
pbr::MeshMaterial3d,
|
||||||
prelude::{
|
prelude::{
|
||||||
children, default, App, AppGizmoBuilder, Assets, ButtonInput, Color, Commands,
|
default, App, AppGizmoBuilder, Assets, BuildChildren, ButtonInput, ChildBuild, Color,
|
||||||
DefaultPlugins, Entity, GizmoConfig, KeyCode, Mesh, Mesh3d, Meshable, Plane3d, PointLight,
|
Commands, DefaultPlugins, Entity, GizmoConfig, KeyCode, Mesh, Mesh3d, Meshable, Plane3d,
|
||||||
Query, Res, ResMut, SpawnRelated, Srgba, StandardMaterial, Startup, Transform, Update,
|
PointLight, Query, Res, ResMut, Srgba, StandardMaterial, Startup, Transform, Update, Vec3,
|
||||||
Vec3, Visibility, Window,
|
Visibility, Window,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
use bevy_inspector_egui::quick::WorldInspectorPlugin;
|
||||||
|
|
||||||
mod bike;
|
mod bike;
|
||||||
mod camera;
|
mod camera;
|
||||||
|
@ -30,6 +31,7 @@ fn main() {
|
||||||
CyberBikePlugin,
|
CyberBikePlugin,
|
||||||
CyberInputPlugin,
|
CyberInputPlugin,
|
||||||
CyberPhysicsPlugin,
|
CyberPhysicsPlugin,
|
||||||
|
WorldInspectorPlugin::new(),
|
||||||
))
|
))
|
||||||
.insert_gizmo_config(
|
.insert_gizmo_config(
|
||||||
PhysicsGizmos {
|
PhysicsGizmos {
|
||||||
|
@ -54,21 +56,25 @@ fn ground_and_light(
|
||||||
mut materials: ResMut<Assets<StandardMaterial>>,
|
mut materials: ResMut<Assets<StandardMaterial>>,
|
||||||
) {
|
) {
|
||||||
let spatial_bundle = (Transform::default(), Visibility::default());
|
let spatial_bundle = (Transform::default(), Visibility::default());
|
||||||
commands.spawn((
|
commands
|
||||||
spatial_bundle,
|
.spawn((
|
||||||
RigidBody::Static,
|
spatial_bundle,
|
||||||
Collider::cuboid(500.0, 5., 500.0),
|
RigidBody::Static,
|
||||||
CollisionMargin(0.1),
|
Collider::cuboid(500.0, 5., 500.0),
|
||||||
ColliderDensity(1000.0),
|
CollisionMargin(0.1),
|
||||||
CollisionLayers::ALL,
|
ColliderDensity(1000.0),
|
||||||
Friction::new(0.9),
|
CollisionLayers::ALL,
|
||||||
children![(
|
Friction::new(0.9),
|
||||||
Mesh3d(meshes.add(Plane3d::default().mesh().size(500.0, 500.0))),
|
))
|
||||||
MeshMaterial3d(materials.add(Color::from(SILVER).with_alpha(0.7))),
|
.with_children(|p| {
|
||||||
Transform::from_xyz(0.0, 2.5, 0.0),
|
let bundle = (
|
||||||
Visibility::Visible,
|
Mesh3d(meshes.add(Plane3d::default().mesh().size(500.0, 500.0))),
|
||||||
)],
|
MeshMaterial3d(materials.add(Color::from(SILVER).with_alpha(0.7))),
|
||||||
));
|
Transform::from_xyz(0.0, 2.5, 0.0),
|
||||||
|
Visibility::Visible,
|
||||||
|
);
|
||||||
|
p.spawn(bundle);
|
||||||
|
});
|
||||||
|
|
||||||
commands.spawn((
|
commands.spawn((
|
||||||
PointLight {
|
PointLight {
|
||||||
|
|
149
src/physics.rs
149
src/physics.rs
|
@ -1,16 +1,16 @@
|
||||||
use avian3d::{math::Scalar, prelude::*};
|
use avian3d::{math::Scalar, prelude::*};
|
||||||
use bevy::prelude::{
|
use bevy::prelude::*;
|
||||||
App, Component, FixedUpdate, IntoScheduleConfigs, Plugin, ResMut, Resource, Startup, Update,
|
|
||||||
};
|
|
||||||
|
|
||||||
const DRAG_COEFF: Scalar = 0.00001;
|
const DRAG_COEFF: Scalar = 0.1;
|
||||||
|
|
||||||
#[derive(Resource, Default, Debug)]
|
#[derive(Resource, Default, Debug, Reflect)]
|
||||||
|
#[reflect(Resource)]
|
||||||
struct CyberLean {
|
struct CyberLean {
|
||||||
pub lean: f32,
|
pub lean: f32,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Resource)]
|
#[derive(Debug, Resource, Reflect)]
|
||||||
|
#[reflect(Resource)]
|
||||||
pub struct CatControllerSettings {
|
pub struct CatControllerSettings {
|
||||||
pub kp: f32,
|
pub kp: f32,
|
||||||
pub kd: f32,
|
pub kd: f32,
|
||||||
|
@ -20,14 +20,14 @@ pub struct CatControllerSettings {
|
||||||
impl Default for CatControllerSettings {
|
impl Default for CatControllerSettings {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
kp: 60.0,
|
kp: 16.0,
|
||||||
kd: 30.0,
|
kd: 2.0,
|
||||||
ki: 0.0,
|
ki: 0.9,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
#[derive(Component, Debug, Clone, Copy, Reflect)]
|
||||||
pub struct CatControllerState {
|
pub struct CatControllerState {
|
||||||
pub roll_integral: f32,
|
pub roll_integral: f32,
|
||||||
pub roll_prev: f32,
|
pub roll_prev: f32,
|
||||||
|
@ -57,17 +57,8 @@ impl CatControllerState {
|
||||||
mod systems {
|
mod systems {
|
||||||
use std::f32::consts::{FRAC_PI_3, FRAC_PI_4};
|
use std::f32::consts::{FRAC_PI_3, FRAC_PI_4};
|
||||||
|
|
||||||
use avian3d::prelude::{
|
use avian3d::prelude::*;
|
||||||
ComputedCenterOfMass, ExternalForce, ExternalTorque, Gravity, LinearVelocity, RayCaster,
|
use bevy::prelude::*;
|
||||||
RayHits, RigidBodyQueryReadOnly,
|
|
||||||
};
|
|
||||||
use bevy::{
|
|
||||||
ecs::system::{Populated, Single},
|
|
||||||
prelude::{
|
|
||||||
ButtonInput, Color, Gizmos, GlobalTransform, KeyCode, Quat, Res, ResMut, Time,
|
|
||||||
Transform, Vec, Vec3, With, Without,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::{CatControllerSettings, CatControllerState, CyberLean, DRAG_COEFF};
|
use super::{CatControllerSettings, CatControllerState, CyberLean, DRAG_COEFF};
|
||||||
use crate::{
|
use crate::{
|
||||||
|
@ -87,8 +78,8 @@ mod systems {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn calculate_lean(
|
pub(super) fn calculate_lean(
|
||||||
bike_state: Single<(&LinearVelocity, &Transform), With<CyberBikeBody>>,
|
bike_state: Query<(&LinearVelocity, &Transform), With<CyberBikeBody>>,
|
||||||
wheels: Populated<&GlobalTransform, With<CyberWheel>>,
|
wheels: Query<&GlobalTransform, With<CyberWheel>>,
|
||||||
input: Res<InputState>,
|
input: Res<InputState>,
|
||||||
gravity: Res<Gravity>,
|
gravity: Res<Gravity>,
|
||||||
mut lean: ResMut<CyberLean>,
|
mut lean: ResMut<CyberLean>,
|
||||||
|
@ -97,7 +88,7 @@ mod systems {
|
||||||
let w1 = wheels.next().unwrap();
|
let w1 = wheels.next().unwrap();
|
||||||
let w2 = wheels.next().unwrap();
|
let w2 = wheels.next().unwrap();
|
||||||
let base = (w1.translation() - w2.translation()).length().abs();
|
let base = (w1.translation() - w2.translation()).length().abs();
|
||||||
let (velocity, xform) = bike_state.into_inner();
|
let (velocity, xform) = bike_state.single();
|
||||||
let vel = velocity.dot(*xform.forward());
|
let vel = velocity.dot(*xform.forward());
|
||||||
let v_squared = vel.powi(2);
|
let v_squared = vel.powi(2);
|
||||||
let steering_angle = yaw_to_angle(input.yaw);
|
let steering_angle = yaw_to_angle(input.yaw);
|
||||||
|
@ -114,34 +105,22 @@ mod systems {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn apply_lean(
|
pub(super) fn apply_lean(
|
||||||
bike_query: Single<(&Transform, &mut ExternalTorque, &mut CatControllerState)>,
|
mut bike_query: Query<(&Transform, &mut ExternalForce, &mut CatControllerState)>,
|
||||||
wheels: Populated<(&WheelState, &GlobalTransform, &CyberWheel)>,
|
wheels: Query<&WheelState>,
|
||||||
time: Res<Time>,
|
time: Res<Time>,
|
||||||
settings: Res<CatControllerSettings>,
|
settings: Res<CatControllerSettings>,
|
||||||
lean: Res<CyberLean>,
|
lean: Res<CyberLean>,
|
||||||
mut gizmos: Gizmos,
|
mut gizmos: Gizmos,
|
||||||
) {
|
) {
|
||||||
let (xform, mut torque, mut control_vars) = bike_query.into_inner();
|
let (xform, mut force, mut control_vars) = bike_query.single_mut();
|
||||||
|
|
||||||
let mut factor = 1.0;
|
let mut factor = 1.0;
|
||||||
let mut rxform = GlobalTransform::default();
|
for wheel in wheels.iter() {
|
||||||
let mut fxform = GlobalTransform::default();
|
if wheel.contact_point.is_none() {
|
||||||
for (wheel_state, xform, cwheel) in wheels.iter() {
|
|
||||||
if wheel_state.contact_point.is_none() {
|
|
||||||
factor -= 0.25;
|
factor -= 0.25;
|
||||||
}
|
}
|
||||||
match cwheel {
|
|
||||||
CyberWheel::Front => {
|
|
||||||
fxform = *xform;
|
|
||||||
}
|
|
||||||
CyberWheel::Rear => {
|
|
||||||
rxform = *xform;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let tork_axis = (rxform.translation() - fxform.translation()).normalize();
|
|
||||||
|
|
||||||
let world_up = Vec3::Y; //xform.translation.normalize();
|
let world_up = Vec3::Y; //xform.translation.normalize();
|
||||||
let rot = Quat::from_axis_angle(*xform.back(), lean.lean);
|
let rot = Quat::from_axis_angle(*xform.back(), lean.lean);
|
||||||
let target_up = rotate_point(&world_up, &rot).normalize();
|
let target_up = rotate_point(&world_up, &rot).normalize();
|
||||||
|
@ -171,14 +150,15 @@ mod systems {
|
||||||
let mag =
|
let mag =
|
||||||
(settings.kp * roll_error) + (settings.ki * integral) + (settings.kd * derivative);
|
(settings.kp * roll_error) + (settings.ki * integral) + (settings.kd * derivative);
|
||||||
if mag.is_finite() {
|
if mag.is_finite() {
|
||||||
//let lean_force = factor * mag * *xform.left();
|
let lean_force = factor * mag * *xform.left();
|
||||||
let tork = factor * mag * tork_axis;
|
force.apply_force_at_point(
|
||||||
|
lean_force,
|
||||||
torque.apply_torque(tork);
|
xform.translation + *xform.up(),
|
||||||
|
xform.translation,
|
||||||
|
);
|
||||||
gizmos.arrow(
|
gizmos.arrow(
|
||||||
xform.translation + *xform.up(),
|
xform.translation + *xform.up(),
|
||||||
xform.translation + *xform.up() + mag * xform.left(),
|
xform.translation + *xform.up() + lean_force,
|
||||||
Color::WHITE,
|
Color::WHITE,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -195,15 +175,12 @@ mod systems {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn suspension(
|
pub(super) fn suspension(
|
||||||
bike_body_query: Single<
|
mut bike_body_query: Query<(&Transform, &mut ExternalForce), With<CyberBikeBody>>,
|
||||||
(&Transform, &ComputedCenterOfMass, &mut ExternalForce),
|
mut wheel_mesh_query: Query<
|
||||||
With<CyberBikeBody>,
|
|
||||||
>,
|
|
||||||
mut wheel_mesh_query: Populated<
|
|
||||||
(&mut Transform, &mut WheelState, &WheelConfig, &CyberWheel),
|
(&mut Transform, &mut WheelState, &WheelConfig, &CyberWheel),
|
||||||
Without<CyberBikeBody>,
|
Without<CyberBikeBody>,
|
||||||
>,
|
>,
|
||||||
caster_query: Populated<(&RayCaster, &RayHits, &CyberWheel)>,
|
caster_query: Query<(&RayCaster, &RayHits, &CyberWheel)>,
|
||||||
time: Res<Time>,
|
time: Res<Time>,
|
||||||
mut gizmos: Gizmos,
|
mut gizmos: Gizmos,
|
||||||
) {
|
) {
|
||||||
|
@ -228,7 +205,7 @@ mod systems {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let (bike_xform, com, mut bike_forces) = bike_body_query.into_inner();
|
let (bike_xform, mut bike_forces) = bike_body_query.single_mut();
|
||||||
|
|
||||||
for (mut xform, mut state, config, wheel) in wheel_mesh_query.iter_mut() {
|
for (mut xform, mut state, config, wheel) in wheel_mesh_query.iter_mut() {
|
||||||
let (caster, hits) = match wheel {
|
let (caster, hits) = match wheel {
|
||||||
|
@ -260,7 +237,11 @@ mod systems {
|
||||||
hit_point + force,
|
hit_point + force,
|
||||||
Color::linear_rgb(1., 0.5, 0.2),
|
Color::linear_rgb(1., 0.5, 0.2),
|
||||||
);
|
);
|
||||||
bike_forces.apply_force_at_point(force, hit_point, bike_xform.translation + com.0);
|
bike_forces.apply_force_at_point(
|
||||||
|
force,
|
||||||
|
caster.global_origin(),
|
||||||
|
bike_xform.translation,
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
xform.translation = config.attach + (caster.direction.as_vec3() * config.rest_dist);
|
xform.translation = config.attach + (caster.direction.as_vec3() * config.rest_dist);
|
||||||
state.reset();
|
state.reset();
|
||||||
|
@ -268,8 +249,8 @@ mod systems {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn wheel_action(
|
pub(super) fn steering(
|
||||||
bike_query: Single<
|
mut bike_query: Query<
|
||||||
(
|
(
|
||||||
&Transform,
|
&Transform,
|
||||||
&LinearVelocity,
|
&LinearVelocity,
|
||||||
|
@ -278,16 +259,20 @@ mod systems {
|
||||||
),
|
),
|
||||||
With<CyberBikeBody>,
|
With<CyberBikeBody>,
|
||||||
>,
|
>,
|
||||||
mut wheels: Populated<(&mut WheelState, &WheelConfig, &CyberWheel)>,
|
mut wheels: Query<(&mut WheelState, &WheelConfig, &CyberWheel)>,
|
||||||
time: Res<Time>,
|
time: Res<Time>,
|
||||||
input: Res<InputState>,
|
input: Res<InputState>,
|
||||||
mut gizmos: Gizmos,
|
mut gizmos: Gizmos,
|
||||||
) {
|
) {
|
||||||
let (bike_xform, bike_vel, mut bike_force, bike_body) = bike_query.into_inner();
|
let Ok((bike_xform, bike_vel, mut bike_force, bike_body)) = bike_query.get_single_mut()
|
||||||
|
else {
|
||||||
|
bevy::log::warn!("No entity for bike_query.");
|
||||||
|
return;
|
||||||
|
};
|
||||||
let bike_vel = bike_vel.0;
|
let bike_vel = bike_vel.0;
|
||||||
|
|
||||||
let dt = time.delta().as_secs_f32();
|
let dt = time.delta().as_secs_f32();
|
||||||
let max_thrust = 500.0;
|
let max_thrust = 2000.0;
|
||||||
let yaw_angle = -yaw_to_angle(input.yaw);
|
let yaw_angle = -yaw_to_angle(input.yaw);
|
||||||
|
|
||||||
for (mut state, config, wheel) in wheels.iter_mut() {
|
for (mut state, config, wheel) in wheels.iter_mut() {
|
||||||
|
@ -300,8 +285,8 @@ mod systems {
|
||||||
let forward = normal.cross(*bike_xform.right());
|
let forward = normal.cross(*bike_xform.right());
|
||||||
let thrust_mag = input.throttle * max_thrust * dt;
|
let thrust_mag = input.throttle * max_thrust * dt;
|
||||||
let (thrust_dir, thrust_force) = match wheel {
|
let (thrust_dir, thrust_force) = match wheel {
|
||||||
CyberWheel::Rear => (forward, thrust_mag),
|
CyberWheel::Rear => (forward, thrust_mag * 0.1),
|
||||||
CyberWheel::Front => (rot * forward, thrust_mag * 0.1),
|
CyberWheel::Front => (rot * forward, thrust_mag),
|
||||||
};
|
};
|
||||||
|
|
||||||
let thrust = thrust_force * thrust_dir;
|
let thrust = thrust_force * thrust_dir;
|
||||||
|
@ -328,11 +313,7 @@ mod systems {
|
||||||
state.sliding = false;
|
state.sliding = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
bike_force.apply_force_at_point(
|
bike_force.apply_force_at_point(force, contact_point, bike_xform.translation);
|
||||||
force,
|
|
||||||
contact_point,
|
|
||||||
bike_xform.translation + bike_body.center_of_mass.0,
|
|
||||||
);
|
|
||||||
gizmos.arrow(
|
gizmos.arrow(
|
||||||
contact_point,
|
contact_point,
|
||||||
contact_point + friction,
|
contact_point + friction,
|
||||||
|
@ -348,35 +329,26 @@ mod systems {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn drag(
|
pub(super) fn drag(
|
||||||
bike_query: Single<
|
mut bike_query: Query<
|
||||||
(
|
(&Transform, &LinearVelocity, &mut ExternalForce),
|
||||||
&Transform,
|
|
||||||
&LinearVelocity,
|
|
||||||
&ComputedCenterOfMass,
|
|
||||||
&mut ExternalForce,
|
|
||||||
),
|
|
||||||
With<CyberBikeBody>,
|
With<CyberBikeBody>,
|
||||||
>,
|
>,
|
||||||
mut gizmos: Gizmos,
|
mut gizmos: Gizmos,
|
||||||
time: Res<Time>,
|
time: Res<Time>,
|
||||||
) {
|
) {
|
||||||
let (xform, vel, com, mut force) = bike_query.into_inner();
|
let (xform, vel, mut force) = bike_query.single_mut();
|
||||||
|
|
||||||
let dt = time.delta_secs();
|
let dt = time.delta_secs();
|
||||||
|
|
||||||
let speed = vel.length_squared();
|
let speed = vel.length();
|
||||||
let dspeed = speed * 0.0000001;
|
let dspeed = speed.powf(1.2) * 0.1;
|
||||||
let dir = vel.normalize_or_zero();
|
let dir = vel.normalize_or_zero();
|
||||||
let drag = -dspeed * dt * DRAG_COEFF * dir;
|
let drag = -dspeed * dt * DRAG_COEFF * dir;
|
||||||
if speed > 0.1 {
|
if speed > 1.0 {
|
||||||
force.apply_force_at_point(
|
force.apply_force_at_point(drag, xform.translation, xform.translation);
|
||||||
drag,
|
|
||||||
xform.translation - (0.2 * *xform.down()),
|
|
||||||
xform.translation + com.0,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bevy::log::debug!("speed: {}, drag force: {}", vel.length(), drag.length());
|
bevy::log::debug!("speed: {}, drag force: {}", speed, drag.length());
|
||||||
|
|
||||||
gizmos.arrow(
|
gizmos.arrow(
|
||||||
xform.translation,
|
xform.translation,
|
||||||
|
@ -386,7 +358,7 @@ mod systems {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn tweak(
|
pub(super) fn tweak(
|
||||||
mut config: Populated<&mut WheelConfig>,
|
mut config: Query<&mut WheelConfig>,
|
||||||
mut keys: ResMut<ButtonInput<KeyCode>>,
|
mut keys: ResMut<ButtonInput<KeyCode>>,
|
||||||
) {
|
) {
|
||||||
let keyset: std::collections::HashSet<_> = keys.get_pressed().collect();
|
let keyset: std::collections::HashSet<_> = keys.get_pressed().collect();
|
||||||
|
@ -423,14 +395,17 @@ mod systems {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
use systems::{apply_lean, calculate_lean, drag, suspension, tweak, wheel_action};
|
use systems::{apply_lean, calculate_lean, drag, steering, suspension, tweak};
|
||||||
|
|
||||||
pub struct CyberPhysicsPlugin;
|
pub struct CyberPhysicsPlugin;
|
||||||
|
|
||||||
impl Plugin for CyberPhysicsPlugin {
|
impl Plugin for CyberPhysicsPlugin {
|
||||||
fn build(&self, app: &mut App) {
|
fn build(&self, app: &mut App) {
|
||||||
app.init_resource::<CatControllerSettings>()
|
app.init_resource::<CatControllerSettings>()
|
||||||
|
.register_type::<CatControllerSettings>()
|
||||||
|
.register_type::<CatControllerState>()
|
||||||
.init_resource::<CyberLean>()
|
.init_resource::<CyberLean>()
|
||||||
|
.register_type::<CyberLean>()
|
||||||
.add_plugins((PhysicsPlugins::default(), PhysicsDebugPlugin::default()))
|
.add_plugins((PhysicsPlugins::default(), PhysicsDebugPlugin::default()))
|
||||||
.insert_resource(SubstepCount(12))
|
.insert_resource(SubstepCount(12))
|
||||||
.add_systems(Startup, |mut gravity: ResMut<Gravity>| {
|
.add_systems(Startup, |mut gravity: ResMut<Gravity>| {
|
||||||
|
@ -438,7 +413,7 @@ impl Plugin for CyberPhysicsPlugin {
|
||||||
})
|
})
|
||||||
.add_systems(
|
.add_systems(
|
||||||
FixedUpdate,
|
FixedUpdate,
|
||||||
(calculate_lean, apply_lean, suspension, wheel_action, drag).chain(),
|
(calculate_lean, apply_lean, suspension, steering, drag).chain(),
|
||||||
)
|
)
|
||||||
.add_systems(Update, tweak);
|
.add_systems(Update, tweak);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue