Skip to main content

PhysicsWorld

Struct PhysicsWorld 

Source
pub struct PhysicsWorld {
    pub gravity: Vector,
    pub integration_parameters: IntegrationParameters,
    pub physics_pipeline: PhysicsPipeline,
    pub islands: IslandManager,
    pub broad_phase: BroadPhaseBvh,
    pub narrow_phase: NarrowPhase,
    pub bodies: RigidBodySet,
    pub colliders: ColliderSet,
    pub impulse_joints: ImpulseJointSet,
    pub multibody_joints: MultibodyJointSet,
    pub ccd_solver: CCDSolver,
}
Expand description

A convenience wrapper that bundles all the Rapier physics state into a single struct.

Rapier intentionally splits its state across many structs (RigidBodySet, ColliderSet, NarrowPhase, etc.) to give you fine-grained control over borrowing. This is important for advanced use cases, but it makes simple setups verbose.

PhysicsWorld gives you a single struct for the common case. All fields are pub, so you can always reach in and borrow individual fields when the borrow checker requires it.

§Example

let mut world = PhysicsWorld::default();

// Create a ground plane
let (_ground, _) = world.insert(
    RigidBodyBuilder::fixed(),
    ColliderBuilder::cuboid(10.0, 0.1, 10.0),
);

// Create a falling ball
let (ball, _) = world.insert(
    RigidBodyBuilder::dynamic().translation(Vector::new(0.0, 5.0, 0.0)),
    ColliderBuilder::ball(0.5),
);

// Simulate 100 steps
for _ in 0..100 {
    world.step();
}

println!("Ball position: {:?}", world.bodies[ball].translation());

Fields§

§gravity: Vector

Gravity applied to all dynamic bodies each step.

§integration_parameters: IntegrationParameters

Parameters controlling the simulation (timestep, solver iterations, etc.).

§physics_pipeline: PhysicsPipeline

The main simulation pipeline that orchestrates each physics step.

§islands: IslandManager

Manages active/sleeping body groups (islands) for efficient simulation.

§broad_phase: BroadPhaseBvh

The broad-phase acceleration structure for fast spatial queries.

§narrow_phase: NarrowPhase

Precise contact and intersection detection between collider pairs.

§bodies: RigidBodySet

All rigid bodies in this world.

§colliders: ColliderSet

All colliders (collision shapes) in this world.

§impulse_joints: ImpulseJointSet

All impulse-based joints (hinges, springs, ropes, etc.).

§multibody_joints: MultibodyJointSet

All multibody joints (kinematic chains, articulations).

§ccd_solver: CCDSolver

The continuous collision detection solver.

Workspace only: not part of a snapshot (see the type docs).

Implementations§

Source§

impl PhysicsWorld

Source

pub fn new() -> Self

Creates a new physics world with default parameters and gravity (0, -9.81, 0).

Source

pub fn step(&mut self)

Advance the simulation by one timestep, using no hooks and no event handler.

This is the simplest way to step. If you need collision events or physics hooks, use step_with_events.

Source

pub fn step_with_events( &mut self, hooks: &dyn PhysicsHooks, events: &dyn EventHandler, )

Advance the simulation by one timestep with custom physics hooks and event handling.

§Example
let (collision_send, collision_recv) = channel();
let (contact_force_send, contact_force_recv) = channel();
let event_handler = ChannelEventCollector::new(collision_send, contact_force_send);

world.step_with_events(&(), &event_handler);

while let Ok(event) = collision_recv.try_recv() {
    println!("Collision event: {:?}", event);
}
Source

pub fn quarantine(&self) -> &Quarantine

The bodies and colliders automatically disabled during the last step because their state became non-finite; see Quarantine.

Source

pub fn insert( &mut self, body: impl Into<RigidBody>, collider: impl Into<Collider>, ) -> (RigidBodyHandle, ColliderHandle)

Insert a rigid body with an attached collider, and return both handles.

This bundles the two most common setup steps — creating a body and attaching its collider — into a single call. For the rare case of a rigid body without any collider (typically an anchor body for joints), use insert_body instead. For compound bodies with multiple colliders, pass the first collider here and use insert_collider with Some(body_handle) for the rest.

§Example
let (body, collider) = world.insert(
    RigidBodyBuilder::dynamic().translation(Vector::new(0.0, 5.0, 0.0)),
    ColliderBuilder::ball(0.5),
);
Source

pub fn insert_body(&mut self, body: impl Into<RigidBody>) -> RigidBodyHandle

Insert a rigid body without any collider, and return its handle.

Most bodies should be inserted together with a collider — prefer insert when possible. Use this method for bodies that truly don’t need a collider, such as anchor bodies used purely as joint attachment points.

§Example
let anchor = world.insert_body(RigidBodyBuilder::fixed());
Source

pub fn remove_body(&mut self, handle: RigidBodyHandle) -> Option<RigidBody>

Remove a rigid body and all its attached colliders and joints.

Returns the removed body, or None if the handle was invalid.

Source

pub fn wake_up(&mut self, handle: RigidBodyHandle, strong: bool)

Wake a sleeping body, forcing it back into the active simulation.

Useful after manually moving a body, applying forces, or otherwise wanting to make sure it gets simulated on the next step. No-op for already-awake bodies, and for fixed bodies (which don’t sleep).

§Parameters
  • strong — if true, the body is guaranteed to stay awake for several frames. If false, it may sleep again immediately if sleep conditions are met.
Source

pub fn wake_up_all(&mut self, strong: bool)

Wake every sleeping body in the world.

Source

pub fn insert_collider( &mut self, collider: impl Into<Collider>, parent: Option<RigidBodyHandle>, ) -> ColliderHandle

Insert a collider, optionally attached to a rigid body, and return its handle.

Pass Some(parent) to attach the collider to a rigid body — its position will then be interpreted relative to its parent. Pass None for a standalone collider, useful for static collision geometry or sensors that don’t need a rigid body.

§Example
let body = world.insert_body(RigidBodyBuilder::dynamic());

// Attached collider.
let attached = world.insert_collider(ColliderBuilder::ball(0.5), Some(body));

// Standalone collider (e.g. static geometry).
let standalone = world.insert_collider(ColliderBuilder::cuboid(10.0, 0.1, 10.0), None);
Source

pub fn remove_collider(&mut self, handle: ColliderHandle) -> Option<Collider>

Remove a collider from the world.

Returns the removed collider, or None if the handle was invalid.

Source

pub fn insert_impulse_joint( &mut self, body1: RigidBodyHandle, body2: RigidBodyHandle, joint: impl Into<GenericJoint>, ) -> ImpulseJointHandle

Insert an impulse joint between two bodies and return its handle.

§Example
let body1 = world.insert_body(RigidBodyBuilder::dynamic());
let body2 = world.insert_body(RigidBodyBuilder::dynamic());
let joint = world.insert_impulse_joint(body1, body2, RevoluteJointBuilder::new(Vector::Z));
Source

pub fn remove_impulse_joint( &mut self, handle: ImpulseJointHandle, ) -> Option<GenericJoint>

Remove an impulse joint.

Returns the removed joint data, or None if the handle was invalid.

Source

pub fn impulse_joints( &self, ) -> impl Iterator<Item = (ImpulseJointHandle, &ImpulseJoint)>

Iterate over every impulse joint in the world as (handle, &joint) pairs.

Source

pub fn impulse_joints_with( &self, body: RigidBodyHandle, ) -> impl Iterator<Item = (RigidBodyHandle, RigidBodyHandle, ImpulseJointHandle, &ImpulseJoint)>

Iterate over every impulse joint attached to the given rigid body.

Each item is (body1, body2, joint_handle, &joint). body1 and body2 are the joint’s endpoints — one of them is always body, the other is the neighbor.

Source

pub fn insert_multibody_joint( &mut self, body1: RigidBodyHandle, body2: RigidBodyHandle, joint: impl Into<GenericJoint>, ) -> Option<MultibodyJointHandle>

Insert a multibody joint between two bodies and return its handle.

Returns None if the joint would create an invalid kinematic chain (e.g. a cycle).

Source

pub fn remove_multibody_joint(&mut self, handle: MultibodyJointHandle)

Remove a multibody joint.

Source

pub fn multibody_joints( &self, ) -> impl Iterator<Item = (MultibodyJointHandle, &MultibodyLinkId, &Multibody, &MultibodyLink)>

Iterate over every multibody joint in the world.

Each item is (joint_handle, &link_id, &multibody, &link).

Source

pub fn multibody_joints_with( &self, body: RigidBodyHandle, ) -> impl Iterator<Item = (RigidBodyHandle, RigidBodyHandle, MultibodyJointHandle)> + '_

Iterate over every multibody joint attached to the given rigid body.

Each item is (body1, body2, joint_handle). body1 and body2 are the joint’s endpoints — one of them is always body, the other is the neighbor.

Source

pub fn query_pipeline(&self) -> QueryPipeline<'_>

Get a QueryPipeline for performing spatial queries (raycasts, shape casts, etc.).

§Example
let query_pipeline = world.query_pipeline();
let ray = Ray::new(Vector::new(0.0, 10.0, 0.0), Vector::new(0.0, -1.0, 0.0));
if let Some((handle, toi)) = query_pipeline.cast_ray(&ray, Real::MAX, true) {
    println!("Hit {:?} at distance {}", handle, toi);
}
Source

pub fn query_pipeline_with_filter<'a>( &'a self, filter: QueryFilter<'a>, ) -> QueryPipeline<'a>

Get a QueryPipeline with a custom QueryFilter.

Source

pub fn cast_ray<'a>( &'a self, ray: &Ray, max_toi: f32, solid: bool, filter: QueryFilter<'a>, ) -> Option<(ColliderHandle, f32)>

Cast a ray and return the first collider hit.

Shorthand for world.query_pipeline_with_filter(filter).cast_ray(...).

Returns Some((collider_handle, distance)), or None if nothing was hit. Pass QueryFilter::default() to consider every collider.

Source

pub fn cast_ray_and_get_normal<'a>( &'a self, ray: &Ray, max_toi: f32, solid: bool, filter: QueryFilter<'a>, ) -> Option<(ColliderHandle, RayIntersection)>

Cast a ray and return the first hit with surface normal information.

Shorthand for world.query_pipeline_with_filter(filter).cast_ray_and_get_normal(...).

Source

pub fn cast_shape<'a>( &'a self, shape_pos: &Pose, shape_vel: Vector, shape: &dyn Shape, options: ShapeCastOptions, filter: QueryFilter<'a>, ) -> Option<(ColliderHandle, ShapeCastHit)>

Cast (sweep) a shape through the world and return the first collider hit.

Shorthand for world.query_pipeline_with_filter(filter).cast_shape(...).

Source

pub fn cast_shape_nonlinear<'a>( &'a self, shape_motion: &NonlinearRigidMotion, shape: &dyn Shape, start_time: f32, end_time: f32, stop_at_penetration: bool, filter: QueryFilter<'a>, ) -> Option<(ColliderHandle, ShapeCastHit)>

Cast a shape with a nonlinear motion and return the first collider hit.

Shorthand for world.query_pipeline_with_filter(filter).cast_shape_nonlinear(...).

Source

pub fn project_point<'a>( &'a self, point: Vector, max_dist: f32, solid: bool, filter: QueryFilter<'a>, ) -> Option<(ColliderHandle, PointProjection)>

Find the closest point on any collider to the given point.

Shorthand for world.query_pipeline_with_filter(filter).project_point(...).

Source

pub fn project_point_and_get_feature<'a>( &'a self, point: Vector, filter: QueryFilter<'a>, max_dist: f32, ) -> Option<(ColliderHandle, PointProjection, FeatureId)>

Project a point onto the closest collider and also return the geometric feature (vertex, edge, or face) that contains the projection.

Shorthand for world.query_pipeline_with_filter(filter).project_point_and_get_feature(...).

Source

pub fn intersect_ray<'a>( &'a self, ray: Ray, max_toi: f32, solid: bool, filter: QueryFilter<'a>, ) -> impl Iterator<Item = (ColliderHandle, &'a Collider, RayIntersection)> + 'a

Iterate over every collider that the given ray passes through.

Unlike cast_ray which stops at the first hit, this yields every collider along the ray’s path. Each item is (handle, &collider, intersection).

Source

pub fn intersect_point<'a>( &'a self, point: Vector, filter: QueryFilter<'a>, ) -> impl Iterator<Item = (ColliderHandle, &'a Collider)> + 'a

Iterate over every collider that contains the given point.

Each item is (handle, &collider).

Source

pub fn intersect_shape<'a>( &'a self, shape_pos: Pose, shape: &'a dyn Shape, filter: QueryFilter<'a>, ) -> impl Iterator<Item = (ColliderHandle, &'a Collider)> + 'a

Iterate over every collider whose shape intersects the given shape positioned at shape_pos.

Each item is (handle, &collider).

Source

pub fn intersect_aabb_conservative<'a>( &'a self, aabb: Aabb, filter: QueryFilter<'a>, ) -> impl Iterator<Item = (ColliderHandle, &'a Collider)> + 'a

Iterate over every collider whose stored AABB intersects the given AABB.

This is conservative: the AABBs used are the ones in the broad-phase BVH, not freshly recomputed collider AABBs. Useful for cheap, broad-strokes proximity queries.

Each item is (handle, &collider).

Source

pub fn contact_pair( &self, collider1: ColliderHandle, collider2: ColliderHandle, ) -> Option<&ContactPair>

Get the contact pair between two specific colliders, if it exists.

Returns None if the two colliders are not in contact or not neighbors in the broad-phase.

Source

pub fn contact_pairs_with( &self, collider: ColliderHandle, ) -> impl Iterator<Item = &ContactPair>

Iterate over all contact pairs involving the given collider.

Source

pub fn contact_pairs(&self) -> impl Iterator<Item = &ContactPair>

Iterate over all contact pairs in the world.

Source

pub fn intersection_pair( &self, collider1: ColliderHandle, collider2: ColliderHandle, ) -> Option<bool>

Check if two specific colliders are intersecting (for sensor colliders).

Returns None if the pair doesn’t exist, Some(true) if intersecting.

Source

pub fn intersection_pairs_with( &self, collider: ColliderHandle, ) -> impl Iterator<Item = (ColliderHandle, &Collider, ColliderHandle, &Collider, bool)> + '_

Iterate over all intersection pairs involving the given collider.

Each item is (handle_a, &collider_a, handle_b, &collider_b, intersecting).

§Mutable access

There is no _mut variant of this method: the same collider may appear in several intersection pairs, so a safe Iterator yielding &mut Collider from a pair iterator isn’t possible in stable Rust. To mutate colliders based on intersection pairs, iterate here to collect the handles you care about, then call ColliderSet::get_pair_mut on self.colliders:

let pairs: Vec<_> = world
    .intersection_pairs_with(collider)
    .map(|(h1, _, h2, _, _)| (h1, h2))
    .collect();
for (h1, h2) in pairs {
    if let (Some(c1), Some(c2)) = world.colliders.get_pair_mut(h1, h2) {
        // mutate c1 and c2…
    }
}
Source

pub fn intersection_pairs( &self, ) -> impl Iterator<Item = (ColliderHandle, &Collider, ColliderHandle, &Collider, bool)> + '_

Iterate over all intersection pairs in the world.

Each item is (handle_a, &collider_a, handle_b, &collider_b, intersecting).

§Mutable access

There is no _mut variant of this method: the same collider may appear in several intersection pairs, so a safe Iterator yielding &mut Collider from a pair iterator isn’t possible in stable Rust. To mutate colliders based on intersection pairs, iterate here to collect the handles you care about, then call ColliderSet::get_pair_mut on self.colliders:

let pairs: Vec<_> = world
    .intersection_pairs()
    .map(|(h1, _, h2, _, _)| (h1, h2))
    .collect();
for (h1, h2) in pairs {
    if let (Some(c1), Some(c2)) = world.colliders.get_pair_mut(h1, h2) {
        // mutate c1 and c2…
    }
}
Source

pub fn rigid_bodies( &self, ) -> impl Iterator<Item = (RigidBodyHandle, &RigidBody)>

Iterate over every rigid body in the world as (handle, &body) pairs.

Source

pub fn rigid_bodies_mut( &mut self, ) -> impl Iterator<Item = (RigidBodyHandle, &mut RigidBody)>

Iterate over every rigid body in the world as (handle, &mut body) pairs.

Source

pub fn active_bodies( &self, ) -> impl Iterator<Item = (RigidBodyHandle, &RigidBody)> + '_

Iterate over only the currently active (awake) rigid bodies.

Sleeping bodies are skipped, as are bodies that never sleep but aren’t part of any active island (e.g. unattached fixed bodies). This is the iterator to use when rendering or syncing transforms, since transforms of sleeping bodies haven’t moved since the last step.

Source

pub fn all_colliders(&self) -> impl Iterator<Item = (ColliderHandle, &Collider)>

Iterate over every collider in the world as (handle, &collider) pairs.

Source

pub fn all_colliders_mut( &mut self, ) -> impl Iterator<Item = (ColliderHandle, &mut Collider)>

Iterate over every collider in the world as (handle, &mut collider) pairs.

Trait Implementations§

Source§

impl Default for PhysicsWorld

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Send + Sync>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> MaybeSync for T
where T: Sync + ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.