### Setup KinematicCharacterController Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/CharacterController.md Example of spawning a kinematic character controller entity with custom configuration in a Bevy system. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; fn setup(mut commands: Commands) { let mut controller = KinematicCharacterController::default(); controller.up = Vec3::Y; controller.offset = CharacterLength::Absolute(0.01); controller.slide = true; controller.apply_impulse_to_dynamic_bodies = true; commands.spawn(( RigidBody::KinematicPositionBased, Collider::capsule_y(0.5, 1.0), controller, Transform::from_xyz(0.0, 1.0, 0.0), )); } ``` -------------------------------- ### Complete Collision Example Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/events.md A full Bevy application demonstrating setup of colliders with ActiveEvents and a system to handle collision events. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; #[derive(Component)] struct Ball; #[derive(Component)] struct Wall; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(RapierPhysicsPlugin::default()) .add_systems(Startup, setup) .add_systems(Update, collision_system) .run(); } fn setup(mut commands: Commands) { // Ball commands.spawn(( Ball, RigidBody::Dynamic, Collider::ball(0.5), Velocity::linear(Vec3::X * 5.0), ActiveEvents::COLLISION_EVENTS, Transform::from_xyz(-5.0, 0.0, 0.0), )); // Wall commands.spawn(( Wall, RigidBody::Fixed, Collider::cuboid(0.1, 5.0, 5.0), Transform::from_xyz(0.0, 0.0, 0.0), )); } fn collision_system( mut collision_events: EventReader, query: Query<&GlobalTransform>, ) { for collision_event in collision_events.read() { match collision_event { CollisionEvent::Started(e1, e2, _) => { if let (Ok(t1), Ok(t2)) = (query.get(*e1), query.get(*e2)) { println!( "Collision at {:?} and {:?}", t1.translation(), t2.translation() ); } } CollisionEvent::Stopped(e1, e2, _) => { println!("Entities {:?} and {:?} separated", e1, e2); } } } } ``` -------------------------------- ### Implement Kinematic Character Controller in Rust Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/CharacterController.md A full example demonstrating the setup of a kinematic character controller, input processing, and movement application within a Bevy application. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; #[derive(Component)] struct Player; fn setup(mut commands: Commands) { let mut controller = KinematicCharacterController { translation: None, custom_shape: None, custom_mass: None, up: Vec3::Y, offset: CharacterLength::Absolute(0.01), slide: true, autostep: Some(CharacterAutostep { max_height: CharacterLength::Absolute(0.5), min_width: CharacterLength::Absolute(0.1), include_dynamic_bodies: false, }), max_slope_climb_angle: 0.785, // 45 degrees min_slope_slide_angle: 1.57, // 90 degrees apply_impulse_to_dynamic_bodies: true, snap_to_ground: Some(CharacterLength::Absolute(0.5)), filter_flags: QueryFilterFlags::default(), filter_groups: None, normal_nudge_factor: 0.1, }; // Create player commands.spawn(( Player, RigidBody::KinematicPositionBased, Collider::capsule_y(0.5, 1.0), controller, Transform::from_xyz(0.0, 2.0, 0.0), GlobalTransform::default(), )); // Create ground commands.spawn(( RigidBody::Fixed, Collider::cuboid(10.0, 0.5, 10.0), Transform::from_xyz(0.0, 0.0, 0.0), )); // Create obstacle to autostep over commands.spawn(( RigidBody::Fixed, Collider::cuboid(0.5, 0.3, 0.5), Transform::from_xyz(2.0, 0.5, 0.0), )); } fn player_input( keyboard: Res>, mut query: Query<&mut KinematicCharacterController, With>, ) { let mut controller = query.single_mut(); let mut translation = Vec3::ZERO; if keyboard.pressed(KeyCode::KeyW) { translation += Vec3::Z; } if keyboard.pressed(KeyCode::KeyS) { translation -= Vec3::Z; } if keyboard.pressed(KeyCode::KeyA) { translation -= Vec3::X; } if keyboard.pressed(KeyCode::KeyD) { translation += Vec3::X; } // Normalize and apply speed if translation != Vec3::ZERO { translation = translation.normalize() * 5.0; } controller.translation = if translation != Vec3::ZERO { Some(translation * 0.016) // 60 FPS } else { None }; } fn apply_character_movement( context: ReadRapierContext, mut query: Query<( &mut Transform, &Collider, &KinematicCharacterController, Entity, ), With>, ) { for (mut transform, collider, controller, _entity) in query.iter_mut() { if let Some(translation) = controller.translation { let options = MoveShapeOptions { up: controller.up, offset: controller.offset, slide: controller.slide, autostep: controller.autostep, max_slope_climb_angle: controller.max_slope_climb_angle, min_slope_slide_angle: controller.min_slope_slide_angle, apply_impulse_to_dynamic_bodies: controller.apply_impulse_to_dynamic_bodies, snap_to_ground: controller.snap_to_ground, normal_nudge_factor: controller.normal_nudge_factor, }; let (collisions, output) = context.move_shape( &options, collider, translation, *transform, &QueryFilter::default(), ); // Update position transform.translation = output.translated; // Debug collisions for collision in collisions { println!("Collided with entity: {:?}", collision.entity); } // Check if on ground if let Some(_ground) = output.ground_info { println!("On ground!"); } } } } fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(RapierPhysicsPlugin::default()) .add_systems(Startup, setup) .add_systems(Update, (player_input, apply_character_movement).chain()) .run(); } ``` -------------------------------- ### Configure Default System Setup Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/configuration.md Disables automatic system setup to allow for manual configuration of PhysicsSet systems. ```rust .add_plugins(RapierPhysicsPlugin::default().with_default_system_setup(false)) ``` -------------------------------- ### CharacterAutostep Configuration Example Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/CharacterController.md Initializes a kinematic controller with custom autostep settings. ```rust let mut controller = KinematicCharacterController::default(); controller.autostep = Some(CharacterAutostep { max_height: CharacterLength::Absolute(0.5), // Up to 0.5m min_width: CharacterLength::Absolute(0.1), // At least 0.1m wide include_dynamic_bodies: false, // Don't step on boxes }); ``` -------------------------------- ### Configure fixed body components Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md Example configuration for a static, fixed body. ```rust ( RigidBody::Fixed, Collider::cuboid(10.0, 0.5, 10.0), Transform::from_xyz(0.0, -1.0, 0.0), GlobalTransform::default(), ) ``` -------------------------------- ### 3D Standard Setup Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/configuration.md Initializes a standard 3D physics environment with custom gravity and timestep settings. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(RapierPhysicsPlugin::default()) .insert_resource(RapierConfiguration { gravity: Vec3::Y * -9.81, physics_pipeline_active: true, scaled_shape_subdivision: 10, force_update_from_transform_changes: false, }) .insert_resource(TimestepMode::Variable { max_dt: 1.0 / 60.0, time_scale: 1.0, substeps: 1, }) .run(); } ``` -------------------------------- ### Configure default system setup Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierPlugin.md Controls whether the plugin automatically sets up physics systems. ```rust pub fn with_default_system_setup(mut self, default_system_setup: bool) -> Self ``` -------------------------------- ### Complete Physics Queries Example Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierContext.md Demonstrates setting up a physics scene and performing raycasts, point projections, and shape intersections. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; #[derive(Component)] struct Sensor; fn setup(mut commands: Commands) { // Ground commands.spawn(( RigidBody::Fixed, Collider::cuboid(10.0, 0.5, 10.0), )); // Dynamic box commands.spawn(( RigidBody::Dynamic, Collider::cuboid(1.0, 1.0, 1.0), Transform::from_xyz(0.0, 5.0, 0.0), )); } fn raycast_system(context: ReadRapierContext) { // Raycast downward from origin if let Some(hit) = context.cast_ray( Vec3::ZERO, Vec3::NEG_Y, 50.0, CollisionGroups::default(), ) { println!("Ray hit at: {:?}", hit.point); println!("Distance: {}", hit.time_of_impact); } } fn point_projection_system(context: ReadRapierContext) { // Find closest surface to a point let projection = context.project_point( Vec3::new(0.0, 2.0, 0.0), CollisionGroups::default(), ); println!("Closest surface: {:?}", projection.point); } fn shape_cast_system(context: ReadRapierContext) { // Check if we can fit a ball at a location let can_fit = !context.intersection_with_shape( Vec3::new(0.0, 2.0, 0.0), Quat::IDENTITY, &Collider::ball(0.5).raw, CollisionGroups::default(), ); println!("Can fit ball: {}", can_fit); } ``` -------------------------------- ### Configure Friction Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Example of manually constructing a Friction component with specific rules. ```rust Friction { coefficient: 0.8, combine_rule: CoefficientCombineRule::Multiply, } ``` -------------------------------- ### PrismaticJoint Usage Examples Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Joints.md Examples of creating vertical and horizontal prismatic joints. ```rust // Vertical slider let joint = PrismaticJoint::new(Vec3::Y); // Horizontal piston let joint = PrismaticJoint::new(Vec3::X); ``` -------------------------------- ### Spawn Collider Example Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Demonstrates spawning a dynamic rigid body with a ball collider and physical properties. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; fn setup(mut commands: Commands) { commands.spawn(( RigidBody::Dynamic, Collider::ball(0.5), // Radius 0.5 Friction::new(0.7), Restitution::new(0.3), )); } ``` -------------------------------- ### Spawn AsyncSceneCollider Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Example of configuring per-mesh collider generation for a scene. ```rust let mut named_shapes = HashMap::new(); named_shapes.insert("Wheel".to_string(), Some(ComputedColliderShape::ConvexHull)); named_shapes.insert("Glass".to_string(), None); // Skip this mesh commands.spawn(( SceneBundle { /* ... */ }, AsyncSceneCollider { shape: Some(ComputedColliderShape::TriMesh(Default::default())), named_shapes, }, )); ``` -------------------------------- ### RopeJoint Usage Example Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Joints.md Example of creating a rope joint with a specific maximum distance. ```rust // Objects can be up to 5 units apart let joint = RopeJoint::new(5.0); ``` -------------------------------- ### Complete Multi-System Event Handling Example Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/events.md Demonstrates setting up sensors and rigid bodies with active events, and processing them using EventReader systems for collision and contact force detection. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; #[derive(Component)] struct Trigger; #[derive(Component)] struct Projectile { damage: f32, } #[derive(Component)] struct Health(f32); fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(RapierPhysicsPlugin::default()) .add_systems(Startup, setup) .add_systems( Update, ( trigger_detection, projectile_hit_detection, health_monitor, ), ) .run(); } fn setup(mut commands: Commands) { // Trigger zone commands.spawn(( Trigger, Sensor, Collider::ball(2.0), ActiveEvents::COLLISION_EVENTS, Transform::from_xyz(0.0, 0.0, 0.0), )); // Projectile commands.spawn(( Projectile { damage: 25.0 }, RigidBody::Dynamic, Collider::ball(0.1), Velocity::linear(Vec3::Z * 10.0), ActiveEvents::COLLISION_EVENTS | ActiveEvents::CONTACT_FORCE_EVENTS, ContactForceEventThreshold(10.0), Transform::from_xyz(0.0, 0.0, -10.0), )); // Health object commands.spawn(( Health(100.0), RigidBody::Fixed, Collider::cuboid(1.0, 1.0, 1.0), ActiveEvents::CONTACT_FORCE_EVENTS, ContactForceEventThreshold(20.0), Transform::from_xyz(0.0, 0.0, 10.0), )); } fn trigger_detection( mut collision_events: EventReader, triggers: Query<&Trigger>, mut commands: Commands, ) { for collision_event in collision_events.read() { if let CollisionEvent::Started(e1, e2, _) = collision_event { if triggers.get(*e1).is_ok() { println!("Entity {:?} entered trigger", e2); } else if triggers.get(*e2).is_ok() { println!("Entity {:?} entered trigger", e1); } } } } fn projectile_hit_detection( mut collision_events: EventReader, projectiles: Query<&Projectile>, mut commands: Commands, ) { for collision_event in collision_events.read() { if let CollisionEvent::Started(e1, e2, _) = collision_event { // Check if e1 is projectile hitting e2 if let Ok(projectile) = projectiles.get(*e1) { println!("Projectile hit! Damage: {}", projectile.damage); commands.entity(*e1).despawn(); } // Check if e2 is projectile hitting e1 else if let Ok(projectile) = projectiles.get(*e2) { println!("Projectile hit! Damage: {}", projectile.damage); commands.entity(*e2).despawn(); } } } } fn health_monitor( mut contact_events: EventReader, mut health_query: Query<(&mut Health, Entity)>, ) { for contact in contact_events.read() { let force = contact.total_force.length(); if let Ok((mut health, _)) = health_query.get_mut(contact.collider1) { let damage = force * 0.01; health.0 -= damage; println!("Entity took {} damage. Health: {:.1}", damage, health.0); } } } ``` -------------------------------- ### Configure Restitution Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Example of creating a highly bouncy Restitution component. ```rust Restitution::new(0.9) // Very bouncy ``` -------------------------------- ### Initialize RapierPhysicsPlugin in Bevy App Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md Standard setup for integrating the physics plugin into a Bevy application. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(RapierPhysicsPlugin::default()) .run(); } ``` -------------------------------- ### Perform a ray cast Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierContext.md Example demonstrating how to cast a ray and handle the intersection result. ```rust fn raycast_example(context: ReadRapierContext) { let hit = context.cast_ray( Vec3::ZERO, // From origin Vec3::Z, // Towards +Z 100.0, // Max distance CollisionGroups::default(), ); if let Some(intersection) = hit { println!("Hit at: {:?}", intersection.point); println!("Distance: {}", intersection.time_of_impact); } } ``` -------------------------------- ### Configure kinematic body components Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md Example configuration for a kinematic body using a character controller. ```rust ( RigidBody::KinematicPositionBased, Collider::capsule_y(0.5, 1.0), KinematicCharacterController::default(), Transform::default(), GlobalTransform::default(), ) ``` -------------------------------- ### Use ReadRapierContext in a system Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierContext.md Example of using ReadRapierContext to access physics query methods. ```rust fn query_physics(context: ReadRapierContext) { // Can call query methods } ``` -------------------------------- ### Spawning a RigidBody with Velocity Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RigidBody.md Example of spawning a dynamic rigid body with an initial velocity configuration. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; fn setup(mut commands: Commands) { commands.spawn(( RigidBody::Dynamic, Velocity { linear: Vec3::new(10.0, 0.0, 0.0), angular: Vec3::new(0.0, 1.0, 0.0) * 2.0, }, )); } ``` -------------------------------- ### Spawn AsyncCollider Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Example of spawning an entity with an AsyncCollider component. ```rust commands.spawn(( SceneBundle { scene: asset_server.load("model.gltf#Scene0"), ..default() }, AsyncCollider(ComputedColliderShape::ConvexHull), )); ``` -------------------------------- ### Configure dynamic body components Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md Example configuration for a dynamic rigid body with velocity, friction, and damping properties. ```rust ( RigidBody::Dynamic, Collider::ball(0.5), Velocity::linear(Vec3::X * 5.0), Friction::new(0.7), Restitution::new(0.3), Damping { linear_damping: 0.1, angular_damping: 0.05 }, LockedAxes::ROTATION_LOCKED_Z, // if needed Transform::default(), GlobalTransform::default(), ) ``` -------------------------------- ### Modify Physics Configuration at Runtime Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierPlugin.md Example of updating physics parameters within a Bevy system. ```rust fn update_physics_speed( mut time_config: ResMut, keyboard: Res>, ) { if keyboard.pressed(KeyCode::Space) { // Slow motion time_config.gravity *= 0.5; // Or change TimestepMode } } ``` -------------------------------- ### Implement Contact Damage System Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/events.md A complete example demonstrating how to use contact force events to apply damage to entities. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; #[derive(Component)] struct HealthBar(f32); fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(RapierPhysicsPlugin::default()) .add_systems(Startup, setup) .add_systems(Update, contact_damage_system) .run(); } fn setup(mut commands: Commands) { // Player commands.spawn(( HealthBar(100.0), RigidBody::Dynamic, Collider::capsule_y(0.5, 1.0), ActiveEvents::CONTACT_FORCE_EVENTS, ContactForceEventThreshold(50.0), // Damage over 50 N Transform::from_xyz(0.0, 1.0, 0.0), )); // Heavy object commands.spawn(( RigidBody::Dynamic, Collider::cuboid(1.0, 1.0, 1.0), Velocity::linear(Vec3::Y * -10.0), // Falling Transform::from_xyz(0.0, 10.0, 0.0), )); } fn contact_damage_system( mut contact_events: EventReader, mut health_query: Query<&mut HealthBar>, ) { for contact in contact_events.read() { let force_magnitude = contact.total_force.length(); let damage = (force_magnitude - 50.0) * 0.1; // Damage = excess force * factor // Apply damage to both entities if let Ok(mut health) = health_query.get_mut(contact.collider1) { health.0 -= damage; println!("Entity 1 took {} damage, health: {}", damage, health.0); } if let Ok(mut health) = health_query.get_mut(contact.collider2) { health.0 -= damage; println!("Entity 2 took {} damage, health: {}", damage, health.0); } } } ``` -------------------------------- ### get_systems(set: PhysicsSet) -> ScheduleConfigs Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierPlugin.md Provides individual physics systems for manual scheduling when default system setup is disabled. ```APIDOC ## get_systems(set: PhysicsSet) -> ScheduleConfigs ### Description Provides individual physics systems for manual scheduling. This is intended for use when `with_default_system_setup(false)` is configured on the plugin. ### Signature `pub fn get_systems(set: PhysicsSet) -> ScheduleConfigs` ### Parameters - **set** (PhysicsSet) - Required - The specific physics stage to retrieve systems for. ### Example ```rust .add_plugins(RapierPhysicsPlugin::default().with_default_system_setup(false)) .add_systems(PostUpdate, RapierPhysicsPlugin::get_systems(PhysicsSet::SyncBackend)) ``` ``` -------------------------------- ### ActiveEvents Usage Example Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Enables collision and contact force events for a collider. ```rust commands.spawn(( Collider::ball(1.0), ActiveEvents::COLLISION_EVENTS | ActiveEvents::CONTACT_FORCE_EVENTS, )); ``` -------------------------------- ### Configure JointLimit constraints Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Joints.md Example of setting angular limits on a RevoluteJoint. ```rust struct JointLimit { pub min: f32, pub max: f32, } let mut joint = RevoluteJoint::new(Vec3::Y); joint.data.limits[0].min = -1.57; // -90° joint.data.limits[0].max = 1.57; // +90° ``` -------------------------------- ### Query CollidingEntities Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Example of iterating through entities colliding with a player. ```rust fn check_collisions( query: Query<(&CollidingEntities, &GlobalTransform), With>, ) { for (colliding, transform) in query.iter() { for entity in colliding.iter() { println!("Player colliding with: {:?}", entity); } } } ``` -------------------------------- ### Modify TimestepMode at Runtime Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/configuration.md Examples of updating the physics configuration dynamically within a system. ```rust fn slow_motion(mut time_config: ResMut) { *time_config = TimestepMode::Variable { max_dt: 1.0 / 60.0, time_scale: 0.5, // Half speed substeps: 1, }; } fn increase_physics_accuracy(mut time_config: ResMut) { *time_config = TimestepMode::Variable { max_dt: 1.0 / 60.0, time_scale: 1.0, substeps: 4, // More accurate }; } ``` -------------------------------- ### Create an ImpulseJoint Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Joints.md Example of connecting a child rigid body to a parent using a RevoluteJoint. ```rust use bevy_rapier3d::prelude::*; // Parent body let parent = commands.spawn(( RigidBody::Dynamic, Collider::ball(0.5), )).id(); // Child body let child = commands.spawn(( RigidBody::Dynamic, Collider::ball(0.3), Transform::from_xyz(2.0, 0.0, 0.0), )).id(); // Joint connecting parent to child commands.entity(child).insert( ImpulseJoint::new(parent, RevoluteJoint::new(Vec3::Y * std::f32::consts::PI / 4.0)) ); ``` -------------------------------- ### Spawn Collider with Mass Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Example of spawning a collider with a fixed mass property. ```rust commands.spawn(( Collider::ball(1.0), ColliderMassProperties::Mass(5.0), // Fixed 5 kg )); ``` -------------------------------- ### Project a point onto a surface Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierContext.md Example of snapping a point to the nearest surface using point projection. ```rust fn snap_to_surface(context: ReadRapierContext) { let projection = context.project_point( Vec3::new(5.0, 5.0, 5.0), CollisionGroups::default(), ); println!("Closest surface point: {:?}", projection.point); println!("Inside something: {}", projection.is_inside); } ``` -------------------------------- ### Composing ExternalForces Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RigidBody.md Example of combining multiple ExternalForce components using arithmetic operators. ```rust let combined = force1 + force2; ``` -------------------------------- ### Applying ExternalForce at a Point Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RigidBody.md Example of creating an ExternalForce that computes torque based on the application point. ```rust let force = ExternalForce::at_point( Vec3::Y * 100.0, // Force magnitude and direction Vec3::new(1.0, 0.0, 0.0), // Application point (world) Vec3::ZERO, // Center of mass (world) ); ``` -------------------------------- ### Spawn entity with Damping Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RigidBody.md Example of spawning a dynamic rigid body with configured linear and angular damping. ```rust commands.spawn(( RigidBody::Dynamic, Damping { linear_damping: 0.1, angular_damping: 0.05, }, )); ``` -------------------------------- ### Create a Compound Collider Instance Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/shapes.md Example of instantiating a compound collider using two ball shapes. ```rust Collider::compound(vec![ (Vec3::ZERO, Quat::IDENTITY, Collider::ball(0.5)), (Vec3::Y * 1.0, Quat::IDENTITY, Collider::ball(0.5)), ]) ``` -------------------------------- ### Configure ActiveCollisionTypes Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Example of spawning a collider with specific active collision type flags. ```rust commands.spawn(( Collider::ball(1.0), ActiveCollisionTypes::DYNAMIC_DYNAMIC | ActiveCollisionTypes::DYNAMIC_STATIC, )); ``` -------------------------------- ### Calculating Linear Velocity at a Point Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RigidBody.md Usage example for computing the linear velocity at a specific world-space point. ```rust let velocity = Velocity::linear(Vec3::X * 5.0); let vel_at_point = velocity.linear_velocity_at_point( Vec3::new(1.0, 0.0, 0.0), Vec3::ZERO, ); ``` -------------------------------- ### CollisionGroups Usage Example Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Configures colliders with specific group memberships and filters to control interaction behavior. ```rust use bevy_rapier3d::geometry::Group; const PLAYER: Group = Group::GROUP_1; const ENEMY: Group = Group::GROUP_2; const WALL: Group = Group::GROUP_3; // Player collides with enemies and walls commands.spawn(( Collider::ball(0.5), CollisionGroups::new(PLAYER, ENEMY | WALL), )); // Enemy collides with player and walls commands.spawn(( Collider::ball(0.5), CollisionGroups::new(ENEMY, PLAYER | WALL), )); ``` -------------------------------- ### Spawn entity with GravityScale Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RigidBody.md Example of spawning a dynamic rigid body with gravity reduced to half strength. ```rust // Half gravity commands.spawn(( RigidBody::Dynamic, GravityScale(0.5), )); ``` -------------------------------- ### Modify RapierConfiguration at runtime Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/configuration.md Examples of modifying physics parameters within Bevy systems using ResMut. ```rust fn toggle_physics(mut config: ResMut) { config.physics_pipeline_active = !config.physics_pipeline_active; } fn change_gravity(mut config: ResMut) { config.gravity = Vec3::new(0.0, -20.0, 0.0); // Double gravity } fn zero_gravity(mut config: ResMut) { config.gravity = Vec3::ZERO; } ``` -------------------------------- ### Apply LockedAxes to Entity Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RigidBody.md Example of spawning a dynamic rigid body with specific translation and rotation axes locked. ```rust commands.spawn(( RigidBody::Dynamic, LockedAxes::TRANSLATION_LOCKED_Z | LockedAxes::ROTATION_LOCKED_X, )); ``` -------------------------------- ### Initialize a Basic Physics Scene in Bevy Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/CommonPatterns.md Sets up a physics world with a fixed ground plane and a dynamic falling box using RapierPhysicsPlugin. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(RapierPhysicsPlugin::default()) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands) { // Camera commands.spawn(Camera3dBundle::default()); // Ground commands.spawn(( RigidBody::Fixed, Collider::cuboid(10.0, 0.5, 10.0), Transform::from_xyz(0.0, 0.0, 0.0), )); // Falling box commands.spawn(( RigidBody::Dynamic, Collider::cuboid(0.5, 0.5, 0.5), Velocity::linear(Vec3::Y * 5.0), Transform::from_xyz(0.0, 5.0, 0.0), )); } ``` -------------------------------- ### Assign Collision Groups Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/Collider.md Example of defining constants for collision group membership. ```rust const PLAYER: Group = Group::GROUP_1; const ENEMY: Group = Group::GROUP_2; const OBSTACLE: Group = Group::GROUP_3; ``` -------------------------------- ### Importing Prelude Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md Import the entire Bevy Rapier prelude for access to common types. ```rust use bevy_rapier3d::prelude::*; ``` -------------------------------- ### Configure custom initialization Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierPlugin.md Sets a custom world initialization strategy for the physics context. ```rust pub fn with_custom_initialization( mut self, default_world_initialization: RapierContextInitialization, ) -> Self ``` ```rust let init = RapierContextInitialization::default_with_length_unit(1.0); .add_plugins(RapierPhysicsPlugin::default().with_custom_initialization(init)) ``` -------------------------------- ### Initialize RapierConfiguration with new Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/configuration.md Creates a new configuration instance with gravity scaled by the provided length unit. ```rust pub fn new(length_unit: Real) -> Self { Self { gravity: Vect::Y * -9.81 * length_unit, physics_pipeline_active: true, scaled_shape_subdivision: 10, force_update_from_transform_changes: false, } } ``` ```rust let config = RapierConfiguration::new(1.0); // Standard scale ``` -------------------------------- ### Check shape intersection Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierContext.md Example of checking if a specific shape can be placed at a given location. ```rust fn check_placement(context: ReadRapierContext) { let valid = context.intersection_with_shape( Vec3::new(0.0, 1.0, 0.0), Quat::IDENTITY, &Collider::ball(0.5).raw, CollisionGroups::default(), ); if !valid { println!("Can place object here"); } } ``` -------------------------------- ### Configure 3D RapierPhysicsPlugin Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierPlugin.md Initializes the physics engine with custom gravity and fixed schedule settings for a 3D Bevy application. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins( RapierPhysicsPlugin::default() .with_length_unit(1.0) // Standard scale .in_fixed_schedule() // Fixed timestep ) .insert_resource(RapierConfiguration { gravity: Vec3::Y * -9.81, physics_pipeline_active: true, scaled_shape_subdivision: 10, force_update_from_transform_changes: false, }) .add_systems(Startup, setup) .add_systems(Update, handle_input) .run(); } fn setup(mut commands: Commands) { // Ground commands.spawn(( RigidBody::Fixed, Collider::cuboid(10.0, 0.5, 10.0), Transform::from_xyz(0.0, -5.0, 0.0), )); // Falling object commands.spawn(( RigidBody::Dynamic, Collider::ball(0.5), Transform::from_xyz(0.0, 5.0, 0.0), )); } fn handle_input( mut config: ResMut, keyboard: Res>, ) { if keyboard.just_pressed(KeyCode::Space) { config.physics_pipeline_active = !config.physics_pipeline_active; } } ``` -------------------------------- ### Manual Physics System Scheduling Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierPlugin.md Use get_systems with with_default_system_setup(false) to manually schedule physics systems in Bevy. ```rust pub fn get_systems(set: PhysicsSet) -> ScheduleConfigs ``` ```rust .add_plugins(RapierPhysicsPlugin::default().with_default_system_setup(false)) .add_systems(PostUpdate, RapierPhysicsPlugin::get_systems(PhysicsSet::SyncBackend)) ``` -------------------------------- ### Run standalone benchmark binary Source: https://github.com/dimforge/bevy_rapier/blob/master/bevy_rapier_benches3d/README.md Executes the custom benchmark binary in release mode to gather performance timings. ```sh cargo run --release --bin bench ``` -------------------------------- ### Run statistical benchmarks with divan Source: https://github.com/dimforge/bevy_rapier/blob/master/bevy_rapier_benches3d/README.md Executes short-lived benchmarks using the divan harness for statistical analysis. ```sh cargo bench -p bevy_rapier_benches3d ``` -------------------------------- ### Using Math Types in Functions Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md Example of utilizing dimension-agnostic math types in a velocity calculation. ```rust use bevy_rapier3d::prelude::{Vect, Rot, Real}; fn calculate_velocity(direction: Vect, magnitude: Real) -> Vect { direction.normalize() * magnitude } ``` -------------------------------- ### RapierConfiguration Methods and Usage Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierPlugin.md Methods for initializing and modifying physics configuration at runtime. ```rust pub fn new(length_unit: Real) -> Self ``` ```rust fn setup(mut rapier_config: ResMut) { // Disable physics temporarily rapier_config.physics_pipeline_active = false; // Change gravity rapier_config.gravity = Vec3::ZERO; // Disable gravity // Resume rapier_config.physics_pipeline_active = true; } ``` -------------------------------- ### Configure 2D RapierPhysicsPlugin Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierPlugin.md Initializes the physics engine for 2D applications using a specific pixel-to-meter ratio. ```rust use bevy::prelude::*; use bevy_rapier2d::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins( RapierPhysicsPlugin::pixels_per_meter(32.0) // 32 px = 1 m ) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands) { // 32 pixels tall platform commands.spawn(( RigidBody::Fixed, Collider::cuboid(10.0, 0.5), // In physics units Transform::from_xy(0.0, -5.0), )); } ``` -------------------------------- ### Configure custom physics scheduling Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md Register the physics plugin in a custom schedule and order systems relative to the simulation step. ```rust .add_plugins(RapierPhysicsPlugin::default().in_schedule(MySchedule)) // Then manually order .add_systems(MySchedule, my_physics_logic.after(PhysicsSet::StepSimulation)) ``` -------------------------------- ### Visualize event flow Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md Diagram showing how physics events are emitted and consumed by Bevy systems. ```text Physics Simulation ↓ Emit CollisionEvent/ContactForceEvent ↓ EventReader in systems ``` -------------------------------- ### Detect Collision Events Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/README.md Reads collision events to identify when two entities start colliding. ```rust fn collision_listener(mut collision_events: EventReader) { for event in collision_events.read() { if let CollisionEvent::Started(e1, e2, _) = event { println!("Collision: {:?} ↔ {:?}", e1, e2); } } } ``` -------------------------------- ### Initialize Rapier Context Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/configuration.md Sets custom initialization parameters like length units when adding the physics plugin. ```rust let init = RapierContextInitialization::default_with_length_unit(1.0); .add_plugins( RapierPhysicsPlugin::default() .with_custom_initialization(init) ) ``` -------------------------------- ### CollisionEvent Enum Definition Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/events.md The core enum representing the start or end of a collision between two entities. ```rust pub enum CollisionEvent { Started(Entity, Entity, CollisionEventFlags), Stopped(Entity, Entity, CollisionEventFlags), } ``` -------------------------------- ### Configure Physics in FixedUpdate Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md Use this configuration to run the physics simulation within the Bevy FixedUpdate schedule. ```rust .add_plugins(RapierPhysicsPlugin::default().in_fixed_schedule()) ``` -------------------------------- ### Implement Multiple Physics Contexts Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md Define custom component markers to manage separate physics worlds independently. ```rust #[derive(Component)] struct PhysicsWorld1; #[derive(Component)] struct PhysicsWorld2; fn system1(context: ReadRapierContext) { // Access world 1 } fn system2(context: ReadRapierContext) { // Access world 2 } ``` -------------------------------- ### Implement character movement using RapierContext Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierContext.md Demonstrates how to use move_shape within a Bevy system to update character position based on collisions. ```rust use bevy_rapier3d::prelude::*; fn move_character( context: ReadRapierContext, mut query: Query<(&mut Transform, &Collider, &KinematicCharacterController)>, ) { for (mut transform, collider, controller) in query.iter_mut() { if let Some(translation) = controller.translation { let options = MoveShapeOptions::default(); let (collisions, output) = context.move_shape( &options, collider, translation, *transform, &QueryFilter::default(), ); transform.translation = output.translated; for collision in collisions { println!("Hit: {:?}", collision.entity); } } } } ``` -------------------------------- ### RapierConfiguration Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierPlugin.md Global physics simulation configuration resource for managing gravity, pipeline state, and shape subdivision. ```APIDOC ## RapierConfiguration ### Description Global physics simulation configuration resource. Users can modify fields directly or use the constructor to initialize settings. ### Fields - **gravity** (Vect) - World gravity vector. - **physics_pipeline_active** (bool) - Enable or disable the physics simulation. - **scaled_shape_subdivision** (u32) - Subdivisions for non-uniform scaled shapes. - **force_update_from_transform_changes** (bool) - Whether to always accept transform changes. ### Methods #### new(length_unit: Real) -> Self Creates a new configuration instance with scaled gravity. ### Example ```rust fn setup(mut rapier_config: ResMut) { rapier_config.physics_pipeline_active = false; rapier_config.gravity = Vec3::ZERO; rapier_config.physics_pipeline_active = true; } ``` ``` -------------------------------- ### RapierPhysicsPlugin Builder Methods Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/api-reference/RapierPlugin.md The RapierPhysicsPlugin provides several builder methods to configure the physics engine before adding it to the Bevy App. ```APIDOC ## RapierPhysicsPlugin Builder Methods ### with_length_unit(length_unit: f32) Sets a scale ratio between the physics world and Bevy transforms. Useful for defining pixels-per-meter in 2D games. ### with_custom_initialization(init: RapierContextInitialization) Sets a custom world initialization strategy for the physics context. ### with_default_system_setup(enabled: bool) Controls whether the plugin automatically sets up physics systems. Set to false to manually configure systems via PhysicsSet. ### pixels_per_meter(pixels_per_meter: f32) A convenience method for 2D games to set the scale ratio. ### with_physics_sets_systems(sets: HashSet) Selectively enables or disables specific physics system sets. ### in_fixed_schedule() Configures the physics simulation to run within the FixedUpdate schedule. ### in_schedule(schedule: impl ScheduleLabel) Configures the physics simulation to run within a custom Bevy schedule. ``` -------------------------------- ### Zero Gravity Space Game Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/configuration.md Sets up a physics environment with gravity disabled. ```rust use bevy::prelude::*; use bevy_rapier3d::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(RapierPhysicsPlugin::default()) .insert_resource(RapierConfiguration { gravity: Vec3::ZERO, // No gravity physics_pipeline_active: true, scaled_shape_subdivision: 10, force_update_from_transform_changes: false, }) .run(); } ``` -------------------------------- ### Exporting Prelude Types Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/module-architecture.md The crate::prelude module re-exports essential types for physics simulation. ```rust pub use crate::control::*; pub use crate::dynamics::*; pub use crate::geometry::*; pub use crate::math::*; pub use crate::pipeline::*; pub use crate::plugin::context::systemparams::*; pub use crate::plugin::context::*; pub use crate::plugin::*; pub use crate::picking_backend::*; // If enabled pub use crate::render::*; // If debug-render enabled ``` -------------------------------- ### Selective Collision Event Handling Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/events.md Example of filtering collision events to process only specific entities tagged with a component. ```rust fn selective_collision_handler( mut collision_events: EventReader, query: Query<&MyTag>, ) { for collision_event in collision_events.read() { match collision_event { CollisionEvent::Started(e1, e2, _) => { // Only care about MyTag entities if query.get(*e1).is_ok() || query.get(*e2).is_ok() { println!("Relevant collision!"); } } _ => {} } } } ``` -------------------------------- ### Apply Forces to Rigid Bodies Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/README.md Configure dynamic bodies with initial velocity and external forces. ```rust commands.spawn(( RigidBody::Dynamic, Collider::ball(0.5), Velocity::linear(Vec3::X * 5.0), ExternalForce { force: Vec3::Y * -9.81, torque: Vec3::ZERO, }, Transform::from_xyz(0.0, 2.0, 0.0), )); ``` -------------------------------- ### RapierConfiguration::new Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/configuration.md Creates a new RapierConfiguration instance with gravity scaled by the provided length unit. ```APIDOC ## RapierConfiguration::new(length_unit: Real) -> Self ### Description Creates a new physics configuration with gravity scaled by the specified length unit. ### Parameters - **length_unit** (Real) - Required - The scale factor for gravity. ### Example ```rust let config = RapierConfiguration::new(1.0); ``` ``` -------------------------------- ### 2D Game with Pixels-Per-Meter Source: https://github.com/dimforge/bevy_rapier/blob/master/_autodocs/configuration.md Sets up a 2D physics environment with a specific pixel-to-meter conversion ratio. ```rust use bevy::prelude::*; use bevy_rapier2d::prelude::*; fn main() { const PPM: f32 = 32.0; // 32 pixels = 1 meter App::new() .add_plugins(DefaultPlugins) .add_plugins(RapierPhysicsPlugin::pixels_per_meter(PPM)) .insert_resource(RapierConfiguration::new(PPM)) .insert_resource(TimestepMode::Fixed { dt: 1.0 / 60.0, substeps: 1, }) .run(); } ```