bike hierarchy is boned

This commit is contained in:
Joe Ardent 2025-04-26 15:18:18 -07:00
parent a675f3e52f
commit 3777f120e7
6 changed files with 716 additions and 1079 deletions

1576
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -4,12 +4,14 @@ version = "0.1.0"
edition = "2024"
[dependencies]
bevy = { version = "0.15", features = ["bevy_dev_tools"] }
bevy-inspector-egui = "0.29"
bevy = { version = "0.16", features = ["bevy_dev_tools", "configurable_error_handler"] }
[dependencies.avian3d]
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"]

View file

@ -1,8 +1,16 @@
use avian3d::{
math::{Scalar, FRAC_PI_2},
prelude::*,
prelude::{
AngularDamping, Collider, ColliderDensity, CollisionLayers, ExternalForce, ExternalTorque,
LinearDamping, RayCaster, RigidBody, SleepingDisabled, SpatialQueryFilter,
TransformInterpolation,
},
};
use bevy::prelude::{
children, AlphaMode, App, Assets, Capsule3d, Color, Commands, Component, Dir3, EntityCommands,
Mesh, Mesh3d, MeshMaterial3d, Name, Plugin, Reflect, ResMut, SpawnRelated, Sphere,
StandardMaterial, Startup, Transform, Vec3, Visibility,
};
use bevy::prelude::*;
use crate::physics::CatControllerState;
@ -24,7 +32,6 @@ pub enum CyberWheel {
}
#[derive(Component, Clone, Copy, Debug, Reflect, Default)]
#[reflect(Component)]
pub struct WheelState {
pub displacement: Scalar,
pub force_normal: Scalar,
@ -40,7 +47,6 @@ impl WheelState {
}
#[derive(Component, Clone, Copy, Debug, Reflect)]
#[reflect(Component)]
#[require(WheelState)]
pub struct WheelConfig {
pub attach: Vec3,
@ -82,41 +88,40 @@ fn spawn_bike(
let body_collider =
Collider::capsule_endpoints(0.5, Vec3::new(0.0, 0.0, -0.65), Vec3::new(0.0, 0.0, 0.8));
commands
.spawn((xform, Visibility::default()))
.insert((
Name::new("body"),
RigidBody::Dynamic,
body_collider,
CollisionLayers::from_bits(1, 1),
SleepingDisabled,
CyberBikeBody,
CatControllerState::default(),
ColliderDensity(1.2),
AngularDamping(0.2),
LinearDamping(0.1),
ExternalForce::ZERO.with_persistence(false),
ExternalTorque::ZERO.with_persistence(false),
))
.with_children(|builder| {
let color = Color::srgb(0.7, 0.05, 0.7);
let mut xform = Transform::default();
xform.rotate_x(FRAC_PI_2);
let pbr_bundle = (
Mesh3d(meshes.add(Capsule3d::new(0.5, 1.45))),
xform,
MeshMaterial3d(materials.add(color)),
);
builder.spawn(pbr_bundle);
spawn_wheels(builder, meshes, materials, builder.parent_entity());
});
let mut body = commands.spawn((xform, Visibility::default()));
body.insert((
Name::new("body"),
RigidBody::Dynamic,
body_collider,
CollisionLayers::from_bits(1, 1),
SleepingDisabled,
CyberBikeBody,
CatControllerState::default(),
ColliderDensity(1.2),
AngularDamping(0.2),
LinearDamping(0.1),
ExternalForce::ZERO.with_persistence(false),
ExternalTorque::ZERO.with_persistence(false),
));
let color = Color::srgb(0.7, 0.05, 0.7);
let mut xform = Transform::default();
xform.rotate_x(FRAC_PI_2);
let pbr_bundle = (
Mesh3d(meshes.add(Capsule3d::new(0.5, 1.45))),
xform,
MeshMaterial3d(materials.add(color)),
);
body.insert(children![pbr_bundle]);
spawn_wheels(&mut body, meshes, materials);
}
fn spawn_wheels(
commands: &mut ChildBuilder,
commands: &mut EntityCommands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
body: Entity,
) {
let mesh: Mesh = Sphere::new(WHEEL_RADIUS).into();
@ -127,7 +132,6 @@ fn spawn_wheels(
commands,
FRONT_ATTACH,
Dir3::new_unchecked(front_rake),
body,
REST_DISTANCE,
CyberWheel::Front,
);
@ -155,7 +159,6 @@ fn spawn_wheels(
commands,
REAR_ATTACH,
Dir3::new_unchecked(rear_rake),
body,
REST_DISTANCE,
CyberWheel::Rear,
);
@ -182,23 +185,22 @@ fn spawn_wheels(
//-************************************************************************
fn wheel_caster(
commands: &mut ChildBuilder,
commands: &mut EntityCommands,
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]));
.with_query_filter(SpatialQueryFilter::from_excluded_entities([commands.id()]));
commands.spawn((caster, wheel));
commands.insert(children![(caster, wheel)]);
}
fn wheel_mesh(
commands: &mut ChildBuilder,
commands: &mut EntityCommands,
meshes: &mut ResMut<Assets<Mesh>>,
materials: &mut ResMut<Assets<StandardMaterial>>,
position: Vec3,
@ -220,7 +222,7 @@ fn wheel_mesh(
CyberWheel::Rear => "rear tire",
};
commands.spawn((
commands.insert(children![(
Name::new(name),
config,
Mesh3d(meshes.add(tire_mesh)),
@ -231,7 +233,7 @@ fn wheel_mesh(
CollisionLayers::NONE,
TransformInterpolation,
wheel,
));
)]);
}
pub struct CyberBikePlugin;

View file

@ -1,4 +1,10 @@
use bevy::{prelude::*, utils::HashSet};
use bevy::{
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;
@ -65,8 +71,8 @@ fn follow_bike(
mut camera: Query<&mut Transform, (With<CyberCameras>, Without<CyberBikeBody>)>,
bike: Query<&Transform, (With<CyberBikeBody>, Without<CyberCameras>)>,
offset: Res<DebugCamOffset>,
) {
let bike_xform = *bike.single();
) -> Result {
let bike_xform = *bike.single()?;
let up = Vec3::Y;
let mut ncx = Transform::from_translation(bike_xform.translation);
@ -75,8 +81,10 @@ fn follow_bike(
ncx.translation += ncx.up() * offset.alt;
ncx.look_at(bike_xform.translation, up);
let mut cam_xform = camera.single_mut();
let mut cam_xform = camera.single_mut()?;
*cam_xform = ncx;
Ok(())
}
pub struct CamPlug;

View file

@ -3,15 +3,15 @@ use avian3d::prelude::{
};
use bevy::{
color::{palettes::css::SILVER, Alpha},
ecs::error::{warn, GLOBAL_ERROR_HANDLER},
pbr::MeshMaterial3d,
prelude::{
default, App, AppGizmoBuilder, Assets, BuildChildren, ButtonInput, ChildBuild, Color,
Commands, DefaultPlugins, Entity, GizmoConfig, KeyCode, Mesh, Mesh3d, Meshable, Plane3d,
PointLight, Query, Res, ResMut, Srgba, StandardMaterial, Startup, Transform, Update, Vec3,
Visibility, Window,
children, default, App, AppGizmoBuilder, Assets, ButtonInput, Color, Commands,
DefaultPlugins, Entity, GizmoConfig, KeyCode, Mesh, Mesh3d, Meshable, Plane3d, PointLight,
Query, Res, ResMut, SpawnRelated, Srgba, StandardMaterial, Startup, Transform, Update,
Vec3, Visibility, Window,
},
};
use bevy_inspector_egui::quick::WorldInspectorPlugin;
mod bike;
mod camera;
@ -24,6 +24,10 @@ use input::CyberInputPlugin;
use physics::CyberPhysicsPlugin;
fn main() {
GLOBAL_ERROR_HANDLER
.set(warn)
.expect("The error handler can only be set once, globally.");
// initialize Bevy App here
let mut app = App::new();
app.add_plugins((
DefaultPlugins,
@ -31,7 +35,6 @@ fn main() {
CyberBikePlugin,
CyberInputPlugin,
CyberPhysicsPlugin,
WorldInspectorPlugin::new(),
))
.insert_gizmo_config(
PhysicsGizmos {
@ -56,25 +59,21 @@ fn ground_and_light(
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let spatial_bundle = (Transform::default(), Visibility::default());
commands
.spawn((
spatial_bundle,
RigidBody::Static,
Collider::cuboid(500.0, 5., 500.0),
CollisionMargin(0.1),
ColliderDensity(1000.0),
CollisionLayers::ALL,
Friction::new(0.9),
))
.with_children(|p| {
let bundle = (
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((
spatial_bundle,
RigidBody::Static,
Collider::cuboid(500.0, 5., 500.0),
CollisionMargin(0.1),
ColliderDensity(1000.0),
CollisionLayers::ALL,
Friction::new(0.9),
children![(
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,
)],
));
commands.spawn((
PointLight {

View file

@ -1,16 +1,16 @@
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;
#[derive(Resource, Default, Debug, Reflect)]
#[reflect(Resource)]
#[derive(Resource, Default, Debug)]
struct CyberLean {
pub lean: f32,
}
#[derive(Debug, Resource, Reflect)]
#[reflect(Resource)]
#[derive(Debug, Resource)]
pub struct CatControllerSettings {
pub kp: f32,
pub kd: f32,
@ -27,7 +27,7 @@ impl Default for CatControllerSettings {
}
}
#[derive(Component, Debug, Clone, Copy, Reflect)]
#[derive(Component, Debug, Clone, Copy)]
pub struct CatControllerState {
pub roll_integral: f32,
pub roll_prev: f32,
@ -58,7 +58,13 @@ mod systems {
use std::f32::consts::{FRAC_PI_3, FRAC_PI_4};
use avian3d::prelude::*;
use bevy::prelude::*;
use bevy::{
ecs::error::BevyError,
prelude::{
ButtonInput, Color, Gizmos, GlobalTransform, KeyCode, Quat, Query, Res, ResMut, Result,
Time, Transform, Vec, Vec3, With, Without,
},
};
use super::{CatControllerSettings, CatControllerState, CyberLean, DRAG_COEFF};
use crate::{
@ -83,12 +89,12 @@ mod systems {
input: Res<InputState>,
gravity: Res<Gravity>,
mut lean: ResMut<CyberLean>,
) {
) -> Result {
let mut wheels = wheels.iter();
let w1 = wheels.next().unwrap();
let w2 = wheels.next().unwrap();
let w1 = wheels.next().ok_or(BevyError::from("oops"))?;
let w2 = wheels.next().ok_or(BevyError::from("oops"))?;
let base = (w1.translation() - w2.translation()).length().abs();
let (velocity, xform) = bike_state.single();
let (velocity, xform) = bike_state.single()?;
let vel = velocity.dot(*xform.forward());
let v_squared = vel.powi(2);
let steering_angle = yaw_to_angle(input.yaw);
@ -102,6 +108,7 @@ mod systems {
} else {
//lean.lean = 0.0;
}
Ok(())
}
pub(super) fn apply_lean(
@ -111,8 +118,8 @@ mod systems {
settings: Res<CatControllerSettings>,
lean: Res<CyberLean>,
mut gizmos: Gizmos,
) {
let (xform, mut force, mut control_vars) = bike_query.single_mut();
) -> Result {
let (xform, mut force, mut control_vars) = bike_query.single_mut()?;
let mut factor = 1.0;
for wheel in wheels.iter() {
@ -163,6 +170,7 @@ mod systems {
);
}
}
Ok(())
}
fn yaw_to_angle(yaw: f32) -> f32 {
@ -183,7 +191,7 @@ mod systems {
caster_query: Query<(&RayCaster, &RayHits, &CyberWheel)>,
time: Res<Time>,
mut gizmos: Gizmos,
) {
) -> Result {
let dt = time.delta().as_secs_f32();
let mut front_caster = &RayCaster::default();
@ -205,7 +213,7 @@ mod systems {
}
}
let (bike_xform, mut bike_forces) = bike_body_query.single_mut();
let (bike_xform, mut bike_forces) = bike_body_query.single_mut()?;
for (mut xform, mut state, config, wheel) in wheel_mesh_query.iter_mut() {
let (caster, hits) = match wheel {
@ -247,6 +255,7 @@ mod systems {
state.reset();
}
}
Ok(())
}
pub(super) fn steering(
@ -263,12 +272,8 @@ mod systems {
time: Res<Time>,
input: Res<InputState>,
mut gizmos: Gizmos,
) {
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;
};
) -> Result {
let (bike_xform, bike_vel, mut bike_force, bike_body) = bike_query.single_mut()?;
let bike_vel = bike_vel.0;
let dt = time.delta().as_secs_f32();
@ -326,6 +331,8 @@ mod systems {
);
}
}
Ok(())
}
pub(super) fn drag(
@ -335,8 +342,8 @@ mod systems {
>,
mut gizmos: Gizmos,
time: Res<Time>,
) {
let (xform, vel, mut force) = bike_query.single_mut();
) -> Result {
let (xform, vel, mut force) = bike_query.single_mut()?;
let dt = time.delta_secs();
@ -359,6 +366,8 @@ mod systems {
xform.translation + drag * 10.,
Color::linear_rgb(1.0, 0.0, 0.0),
);
Ok(())
}
pub(super) fn tweak(
@ -406,10 +415,7 @@ pub struct CyberPhysicsPlugin;
impl Plugin for CyberPhysicsPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<CatControllerSettings>()
.register_type::<CatControllerSettings>()
.register_type::<CatControllerState>()
.init_resource::<CyberLean>()
.register_type::<CyberLean>()
.add_plugins((PhysicsPlugins::default(), PhysicsDebugPlugin::default()))
.insert_resource(SubstepCount(12))
.add_systems(Startup, |mut gravity: ResMut<Gravity>| {