### ShapeCaster Setup and Hit Detection Example Source: https://docs.rs/avian2d/latest/src/avian2d/spatial_query/shape_caster.rs.html?search=u32+-%3E+bool This example demonstrates how to spawn a ShapeCaster with a specific shape and direction, and how to iterate over detected hits. Ensure the appropriate Avian2D feature (2D or 3D) and Bevy are included. ```rust use crate::prelude::*; use bevy::prelude::*; /// A component used for [shapecasting](spatial_query#shapecasting). /// /// **Shapecasting** is a type of [spatial query](spatial_query) where a shape travels along a straight /// line and computes hits with colliders. This is often used to determine how far an object can move /// in a direction before it hits something. /// /// Each shapecast is defined by a `shape` (a [`Collider`]), its local `shape_rotation`, a local `origin` and /// a local `direction`. The [`ShapeCaster`] will find each hit and add them to the [`ShapeHits`] component in /// the order of distance. /// /// Computing lots of hits can be expensive, especially against complex geometry, so the maximum number of hits /// is one by default. This can be configured through the `max_hits` property. /// /// The [`ShapeCaster`] is the easiest way to handle simple shapecasting. If you want more control and don't want /// to perform shapecasts on every frame, consider using the [`SpatialQuery`] system parameter. /// /// # Hit Count and Order /// /// The results of a shapecast are in an arbitrary order by default. You can iterate over them in the order of /// distance with the [`ShapeHits::iter_sorted`] method. /// /// You can configure the maximum amount of hits for a shapecast using `max_hits`. By default this is unbounded, /// so you will get all hits. When the number or complexity of colliders is large, this can be very /// expensive computationally. Set the value to whatever works best for your case. /// /// Note that when there are more hits than `max_hits`, **some hits will be missed**. /// To guarantee that the closest hit is included, you should set `max_hits` to one or a value that /// is enough to contain all hits. /// /// # Example /// /// ``` /// # #[cfg(feature = "2d")] /// # use avian2d::prelude::*; /// # #[cfg(feature = "3d")] /// use avian3d::prelude::*; /// use bevy::prelude::*; /// /// # #[cfg(all(feature = "3d", feature = "f32"))] /// fn setup(mut commands: Commands) { /// // Spawn a shape caster with a ball shape moving right starting from the origin /// commands.spawn(ShapeCaster::new( /// #[cfg_attr(feature = "2d", doc = " Collider::circle(0.5),")] /// #[cfg_attr(feature = "3d", doc = " Collider::sphere(0.5),")] /// Vec3::ZERO, /// Quat::default(), /// Dir3::X, /// )); /// } /// /// fn print_hits(query: Query<(&ShapeCaster, &ShapeHits)>) { /// for (shape_caster, hits) in &query { /// for hit in hits.iter() { /// println!("Hit entity {}", hit.entity); /// } /// } /// } /// ``` #[derive(Component, Clone, Debug, Reflect)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))] #[reflect(Debug, Component)] #[component(on_add = on_add_shape_caster)] #[require(ShapeHits)] pub struct ShapeCaster { /// Controls if the shape caster is enabled. pub enabled: bool, /// The shape being cast represented as a [`Collider`]. #[reflect(ignore)] pub shape: Collider, /// The local origin of the shape relative to the [`Position`] and [`Rotation`] /// of the shape caster entity or its parent. /// /// To get the global origin, use the `global_origin` method. pub origin: Vector, /// The global origin of the shape. global_origin: Vector, /// The local rotation of the shape being cast relative to the [`Rotation`] /// of the shape caster entity or its parent. Expressed in radians. /// /// To get the global shape rotation, use the `global_shape_rotation` method. #[cfg(feature = "2d")] pub shape_rotation: Scalar, /// The local rotation of the shape being cast relative to the [`Rotation`] /// of the shape caster entity or its parent. /// /// To get the global shape rotation, use the `global_shape_rotation` method. #[cfg(feature = "3d")] pub shape_rotation: Quaternion, /// The global rotation of the shape. #[cfg(feature = "2d")] global_shape_rotation: Scalar, /// The global rotation of the shape. #[cfg(feature = "3d")] global_shape_rotation: Quaternion, /// The local direction of the shapecast relative to the [`Rotation`] of the shape caster entity or its parent. /// /// To get the global direction, use the `global_direction` method. pub direction: Dir, /// The global direction of the shapecast. global_direction: Dir, } ``` -------------------------------- ### Raycasting Example: Setup and Hit Printing Source: https://docs.rs/avian2d/latest/avian2d/spatial_query/struct.RayCaster.html Demonstrates how to spawn a RayCaster and process its hits. Ensure colliders are also spawned for hits to occur. The `iter_sorted` method provides hits ordered by distance. ```rust use avian3d::prelude::*; use bevy::prelude::*; fn setup(mut commands: Commands) { // Spawn a ray at the center going right commands.spawn(RayCaster::new(Vec3::ZERO, Dir3::X)); // ...spawn colliders and other things } fn print_hits(query: Query<(&RayCaster, &RayHits)>) { for (ray, hits) in &query { // For the faster iterator that isn't sorted, use `.iter()` for hit in hits.iter_sorted() { println!( "Hit entity {} at {} with normal {}", hit.entity, ray.origin + *ray.direction * hit.distance, hit.normal, ); } } } ``` -------------------------------- ### Example: Setup and System for CollidingEntities Source: https://docs.rs/avian2d/latest/avian2d/collision/collider/struct.CollidingEntities.html?search= Demonstrates how to add the CollidingEntities component to a dynamic rigid body and how to create a system to query and print colliding entities. Ensure you have the necessary Avian2D and Bevy prelude imports. ```rust use avian2d::prelude::*; use bevy::prelude::*; fn setup(mut commands: Commands) { commands.spawn(( RigidBody::Dynamic, Collider::capsule(0.5, 1.5), // Add the `CollidingEntities` component to read entities colliding with this entity. CollidingEntities::default(), )); } fn my_system(query: Query<(Entity, &CollidingEntities)>) { for (entity, colliding_entities) in &query { println!( "{} is colliding with the following entities: {:?}", entity, colliding_entities, ); } } ``` -------------------------------- ### Example: Setting up Physics Debug Rendering in Bevy Source: https://docs.rs/avian2d/latest/src/avian2d/debug_render/configuration.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to enable the `PhysicsDebugPlugin` in a Bevy application to visualize physics entities. This setup allows for the rendering of colliders, AABBs, and other physics-related debug information. ```rust use avian2d::prelude::* use bevy::prelude::* fn main() { App::new() .add_plugins((DefaultPlugins, PhysicsPlugins::default(), PhysicsDebugPlugin)) .run(); } fn setup(mut commands: Commands) { // This rigid body and its collider and AABB will get rendered commands.spawn((RigidBody::Dynamic, Collider::circle(0.5), DebugRender::default().with_collider_color(Color::srgb(1.0, 0.0, 0.0)))); } ``` -------------------------------- ### Basic Physics Debugging Setup with Bevy Source: https://docs.rs/avian2d/latest/avian2d/debug_render/struct.DebugRender.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to set up a Bevy application with Avian2D physics and enable debug rendering. This example shows spawning an entity with a RigidBody, Collider, and a custom DebugRender configuration. ```rust use avian2d::prelude::*; use bevy::prelude::*; fn main() { App::new() .add_plugins((DefaultPlugins, PhysicsPlugins::default(), PhysicsDebugPlugin)) .run(); } fn setup(mut commands: Commands) { // This rigid body and its collider and AABB will get rendered commands.spawn((RigidBody::Dynamic, Collider::circle(0.5), // Overwrite default collider color (optional) DebugRender::default().with_collider_color(Color::srgb(1.0, 0.0, 0.0)), )); } ``` -------------------------------- ### Example of Collider Hierarchy Setup Source: https://docs.rs/avian2d/latest/src/avian2d/collision/collider/collider_hierarchy/mod.rs.html Demonstrates how to spawn entities with RigidBody, Collider, and children colliders. All colliders will be attached to the parent rigid body by default. ```rust # use avian2d::prelude::* # use bevy::prelude::* # fn setup(mut commands: Commands) { commands.spawn(( RigidBody::Dynamic, Collider::capsule(0.5, 1.5), children![ (Collider::capsule(0.5, 1.5), Transform::from_xyz(-2.0, 0.0, 0.0)), (Collider::capsule(0.5, 1.5), Transform::from_xyz(2.0, 0.0, 0.0)) ] )); # } ``` -------------------------------- ### Observing CollisionStart Events Source: https://docs.rs/avian2d/latest/avian2d/collision/collision_events/struct.CollisionStart.html?search=std%3A%3Avec Example of how to observe CollisionStart events using Bevy's observer pattern, allowing for immediate reaction to collision starts. ```APIDOC ## Example: Observing CollisionStart ```rust use avian2d::prelude::*; use bevy::prelude::*; #[derive(Component)] struct Player; #[derive(Component)] struct PressurePlate; fn setup_pressure_plates(mut commands: Commands) { commands.spawn(( PressurePlate, Collider::rectangle(1.0, 1.0), Sensor, // Enable collision events for this entity. CollisionEventsEnabled, )) .observe(on_player_stepped_on_plate); } fn on_player_stepped_on_plate(event: On, player_query: Query<&Player>) { // `colider1` and `body1` refer to the event target and its body. // `collider2` and `body2` refer to the other collider and its body. let pressure_plate = event.collider1; let other_entity = event.collider2; if player_query.contains(other_entity) { println!("Player {other_entity} stepped on pressure plate {pressure_plate}"); } } ``` ``` -------------------------------- ### Setup ShapeCaster Source: https://docs.rs/avian2d/latest/src/avian2d/spatial_query/mod.rs.html Example of spawning a ShapeCaster with a sphere shape. Ensure the '3d' feature is enabled. ```rust #[cfg(all(feature = "3d", feature = "f32"))] fn setup(mut commands: Commands) { // Spawn a shape caster with a sphere shape at the center travelling right commands.spawn(ShapeCaster::new( Collider::sphere(0.5), // Shape Vec3::ZERO, // Origin Quat::default(), // Shape rotation Dir3::X // Direction )); // ...spawn colliders and other things } ``` -------------------------------- ### Raycasting Example Source: https://docs.rs/avian2d/latest/src/avian2d/spatial_query/ray_caster.rs.html Demonstrates how to spawn a RayCaster and process its hits. This example assumes a 3D context with f32 precision. ```rust # #[cfg(feature = "2d")] # use avian2d::prelude::*; # #[cfg(feature = "3d")] use avian3d::prelude::*; use bevy::prelude::*; # #[cfg(all(feature = "3d", feature = "f32"))] # fn setup(mut commands: Commands) { // Spawn a ray at the center going right commands.spawn(RayCaster::new(Vec3::ZERO, Dir3::X)); // ...spawn colliders and other things # } # #[cfg(all(feature = "3d", feature = "f32"))] fn print_hits(query: Query<(&RayCaster, &RayHits)>) { for (ray, hits) in &query { // For the faster iterator that isn't sorted, use `.iter()` for hit in hits.iter_sorted() { println!( "Hit entity {} at {} with normal {}", hit.entity, ray.origin + *ray.direction * hit.distance, hit.normal, ); } } } ``` -------------------------------- ### IslandPlugin Setup Source: https://docs.rs/avian2d/latest/src/avian2d/dynamics/solver/islands/mod.rs.html?search=std%3A%3Avec This code demonstrates the setup for the `IslandPlugin` within a Bevy application. It initializes the `PhysicsIslands` resource and registers `BodyIslandNode` for `SolverBody` components. ```rust use bevy::prelude::*; use crate::dynamics::solver::solver_body::SolverBody; /// A plugin for managing [`PhysicsIsland`]s. /// /// See the [module-level documentation](self) for more information. pub struct IslandPlugin; impl Plugin for IslandPlugin { fn build(&self, app: &mut App) { app.init_resource::(); // Insert `BodyIslandNode` for each `SolverBody`. app.register_required_components::(); // Add `BodyIslandNode` for each dynamic and kinematic rigid body // when the associated rigid body is enabled. app.add_observer( |trigger: On, rb_query: Query<&RigidBody>, mut commands: Commands| { let Ok(rb) = rb_query.get(trigger.entity) else { return; }; if rb.is_dynamic() || rb.is_kinematic() { commands .entity(trigger.entity) .try_insert(BodyIslandNode::default()); } }, ); app.add_observer( |trigger: On, rb_query: Query< &RigidBody, ( // The body still has `Disabled` at this point, // and we need to include in the query to match against the entity. With, Without, ), >, mut commands: Commands| { let Ok(rb) = rb_query.get(trigger.entity) else { return; }; ``` -------------------------------- ### Raycasting Example Source: https://docs.rs/avian2d/latest/src/avian2d/spatial_query/ray_caster.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to spawn a RayCaster and iterate over its sorted hits. This example assumes a 3D context with f32 precision. ```rust use crate::prelude::*; use bevy::prelude::*; #[derive(Component, Clone, Debug, PartialEq, Reflect)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))] #[reflect(Debug, Component, PartialEq)] #[component(on_add = on_add_ray_caster)] #[require(RayHits)] pub struct RayCaster { /// Controls if the ray caster is enabled. pub enabled: bool, /// The local origin of the ray relative to the [`Position`] and [`Rotation`] of the ray entity or its parent. /// /// To get the global origin, use the `global_origin` method. pub origin: Vector, /// The global origin of the ray. global_origin: Vector, /// The local direction of the ray relative to the [`Rotation`] of the ray entity or its parent. /// /// To get the global direction, use the `global_direction` method. pub direction: Dir, /// The global direction of the ray. global_direction: Dir, /// The maximum number of hits allowed. /// /// When there are more hits than `max_hits`, **some hits will be missed**. /// To guarantee that the closest hit is included, you should set `max_hits` to one or a value that /// is enough to contain all hits. pub max_hits: u32, /// The maximum distance the ray can travel. /// /// By default this is infinite, so the ray will travel until all hits up to `max_hits` have been checked. #[doc(alias = "max_time_of_impact")] pub max_distance: Scalar, /// Controls how the ray behaves when the ray origin is inside of a [collider](Collider). /// /// If `true`, shapes will be treated as solid, and the ray cast will return with a distance of `0.0` /// if the ray origin is inside of the shape. Otherwise, shapes will be treated as hollow, and the ray /// will always return a hit at the shape's boundary. pub solid: bool, /// If true, the ray caster ignores hits against its own [`Collider`]. This is the default. pub ignore_self: bool, /// Rules that determine which colliders are taken into account in the ray cast. pub query_filter: SpatialQueryFilter, } #[cfg(all(feature = "3d", feature = "f32"))] fn setup(mut commands: Commands) { // Spawn a ray at the center going right commands.spawn(RayCaster::new(Vec3::ZERO, Dir3::X)); // ...spawn colliders and other things } #[cfg(all(feature = "3d", feature = "f32"))] fn print_hits(query: Query<(&RayCaster, &RayHits)>) { for (ray, hits) in &query { // For the faster iterator that isn't sorted, use `.iter()` for hit in hits.iter_sorted() { println!( "Hit entity {} at {} with normal {}", hit.entity, ray.origin + *ray.direction * hit.distance, hit.normal, ); } } } ``` -------------------------------- ### Finish Plugin Setup Source: https://docs.rs/avian2d/latest/avian2d/collision/narrow_phase/struct.NarrowPhasePlugin.html?search=std%3A%3Avec Completes the setup of the NarrowPhasePlugin after all other plugins have been built. This is useful for plugins that have asynchronous initialization or depend on other plugins' setup. ```rust fn finish(&self, app: &mut App) ``` -------------------------------- ### Raycasting Example in Avian2D/3D Source: https://docs.rs/avian2d/latest/src/avian2d/spatial_query/ray_caster.rs.html?search=std%3A%3Avec This example demonstrates how to set up a RayCaster in a 3D Bevy application and how to process the resulting RayHits. It shows spawning a ray and iterating through sorted hits to print information about each intersection. ```rust use crate::prelude::* use bevy::prelude::* #[cfg(all(feature = "3d", feature = "f32"))] fn setup(mut commands: Commands) { // Spawn a ray at the center going right commands.spawn(RayCaster::new(Vec3::ZERO, Dir3::X)); // ...spawn colliders and other things } #[cfg(all(feature = "3d", feature = "f32"))] fn print_hits(query: Query<(&RayCaster, &RayHits)>) { for (ray, hits) in &query { // For the faster iterator that isn't sorted, use `.iter()` for hit in hits.iter_sorted() { println!( "Hit entity {} at {} with normal {}", hit.entity, ray.origin + *ray.direction * hit.distance, hit.normal, ); } } } ``` -------------------------------- ### Finish ColliderTransformPlugin Setup Source: https://docs.rs/avian2d/latest/avian2d/collision/collider/collider_transform/struct.ColliderTransformPlugin.html Completes the setup of the ColliderTransformPlugin after all other registered plugins are ready. This is essential for plugins that depend on the asynchronous completion of other plugins. ```rust fn finish(&self, _app: &mut App) ``` -------------------------------- ### Example: Spawning Entities with Collider Constructors Source: https://docs.rs/avian2d/latest/src/avian2d/collision/collider/constructor.rs.html?search=u32+-%3E+bool Demonstrates how to spawn entities with different ColliderConstructor types. This example shows how to create a 2D circle collider and a 3D convex hull collider from a mesh. ```rust use avian2d::prelude::*; use bevy::prelude::*; fn setup(mut commands: Commands, mut assets: ResMut, mut meshes: Assets) { // Spawn a circle with radius 2 commands.spawn(( ColliderConstructor::Circle { radius: 2.0 }, Mesh2d(meshes.add(Circle::new(2.0))), )); } ``` ```rust use avian3d::prelude::*; use bevy::prelude::*; fn setup(mut commands: Commands, mut assets: ResMut, mut meshes: Assets) { // Spawn a cube with a convex hull collider generated from the mesh commands.spawn(( ColliderConstructor::ConvexHullFromMesh, Mesh3d(meshes.add(Cuboid::default())), )); } ``` -------------------------------- ### HashSet Length Example Source: https://docs.rs/avian2d/latest/avian2d/collision/collider/struct.CollidingEntities.html Illustrates how to get the number of elements in a HashSet, which can be used with CollidingEntities. ```rust let mut map = HashSet::new(); assert_eq!(map.len(), 0); map.insert("foo"); assert_eq!(map.len(), 1); ``` -------------------------------- ### Example: Enabling and Configuring PhysicsDebugPlugin Source: https://docs.rs/avian2d/latest/avian2d/debug_render/struct.PhysicsDebugPlugin.html Demonstrates how to add the PhysicsDebugPlugin to a Bevy application and configure global debug rendering settings. ```rust use avian2d::prelude::*; use bevy::prelude::*; fn main() { App::new() .add_plugins(( DefaultPlugins, PhysicsPlugins::default(), // Enables debug rendering PhysicsDebugPlugin, )) // Overwrite default debug rendering configuration (optional) .insert_gizmo_config( PhysicsGizmos { aabb_color: Some(Color::WHITE), ..default() }, GizmoConfig::default(), ) .run(); } fn setup(mut commands: Commands) { // This rigid body and its collider and AABB will get rendered commands.spawn(( RigidBody::Dynamic, Collider::circle(0.5), // Overwrite default collider color (optional) DebugRender::default().with_collider_color(Color::srgb(1.0, 0.0, 0.0)), )); } ``` -------------------------------- ### Move and Slide Character Controller Example Source: https://docs.rs/avian2d/latest/src/avian2d/character_controller/move_and_slide.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the move_and_slide function to control a character's movement, including handling collisions and updating velocity. This example is suitable for 2D physics simulations. ```rust use bevy::prelude::* use std::collections::HashSet; #[cfg_attr(feature = "2d", doc = "use avian2d::{prelude::*, math::{Vector, AdjustPrecision as _, AsF32 as _}} #[derive(Component)] struct CharacterController { velocity: Vector, } fn perform_move_and_slide( player: Single<(Entity, &Collider, &mut CharacterController, &mut Transform)>, move_and_slide: MoveAndSlide, time: Res