pub struct Collider { /* private fields */ }
Expand description

A collider used for detecting collisions and generating contacts.

§Creation

Collider has tons of methods for creating colliders of various shapes:

// Create a ball collider with a given radius
commands.spawn(Collider::sphere(0.5));
// Create a capsule collider with a given height and radius
commands.spawn(Collider::capsule(2.0, 0.5));

Colliders on their own only detect contacts and generate collision events. To make colliders apply contact forces, they have to be attached to rigid bodies:

use bevy::prelude::*;
use bevy_xpbd_3d::prelude::*;

// Spawn a dynamic body that falls onto a static platform
fn setup(mut commands: Commands) {
    commands.spawn((
        RigidBody::Dynamic,
        Collider::sphere(0.5),
        TransformBundle::from_transform(Transform::from_xyz(0.0, 2.0, 0.0)),
    ));
    commands.spawn((RigidBody::Static, Collider::cuboid(5.0, 0.5, 5.0)));
}

Colliders can be further configured using various components like Friction, Restitution, Sensor, and CollisionLayers.

In addition, Bevy XPBD automatically adds some other components for colliders, like the following:

Colliders can also be generated automatically from meshes and scenes. See AsyncCollider and AsyncSceneCollider.

§Multiple colliders

It can often be useful to attach multiple colliders to the same rigid body.

This can be done in two ways. Either use Collider::compound to have one collider that consists of many shapes, or for more control, spawn several collider entities as the children of a rigid body:

use bevy::prelude::*;
use bevy_xpbd_3d::prelude::*;

fn setup(mut commands: Commands) {
    // Spawn a rigid body with one collider on the same entity and two as children
    commands
        .spawn((RigidBody::Dynamic, Collider::sphere(0.5)))
        .with_children(|children| {
            // Spawn the child colliders positioned relative to the rigid body
            children.spawn((
                Collider::sphere(0.5),
                TransformBundle::from_transform(Transform::from_xyz(2.0, 0.0, 0.0)),
            ));
            children.spawn((
                Collider::sphere(0.5),
                TransformBundle::from_transform(Transform::from_xyz(-2.0, 0.0, 0.0)),
            ));
        });
}

Colliders can be arbitrarily nested and transformed relative to the parent. The rigid body that a collider is attached to can be accessed using the ColliderParent component.

The benefit of using separate entities for the colliders is that each collider can have its own friction, restitution, collision layers, and other configuration options, and they send separate collision events.

§See more

§Advanced usage

Internally, Collider uses the shapes provided by parry. If you want to create a collider using these shapes, you can simply use Collider::from(SharedShape::some_method()).

To get a reference to the internal SharedShape, you can use the Collider::shape() or Collider::shape_scaled() methods.

Implementations§

source§

impl Collider

source

pub fn shape(&self) -> &SharedShape

Returns the raw unscaled shape of the collider.

source

pub fn shape_scaled(&self) -> &SharedShape

Returns the shape of the collider with the scale from its GlobalTransform applied.

source

pub fn set_shape(&mut self, shape: SharedShape)

Sets the unscaled shape of the collider. The collider’s scale will be applied to this shape.

source

pub fn scale(&self) -> Vector

Returns the global scale of the collider.

source

pub fn set_scale(&mut self, scale: Vector, num_subdivisions: u32)

Set the global scaling factor of this shape.

If the scaling factor is not uniform, and the scaled shape can’t be represented as a supported shape, the shape is approximated as a convex polygon or polyhedron using num_subdivisions.

For example, if a ball was scaled to an ellipse, the new shape would be approximated.

source

pub fn project_point( &self, translation: impl Into<Position>, rotation: impl Into<Rotation>, point: Vector, solid: bool ) -> (Vector, bool)

Projects the given point onto self transformed by translation and rotation. The returned tuple contains the projected point and whether it is inside the collider.

If solid is true and the given point is inside of the collider, the projection will be at the point. Otherwise, the collider will be treated as hollow, and the projection will be at the collider’s boundary.

source

pub fn distance_to_point( &self, translation: impl Into<Position>, rotation: impl Into<Rotation>, point: Vector, solid: bool ) -> Scalar

Computes the minimum distance between the given point and self transformed by translation and rotation.

If solid is true and the given point is inside of the collider, the returned distance will be 0.0. Otherwise, the collider will be treated as hollow, and the distance will be the distance to the collider’s boundary.

source

pub fn contains_point( &self, translation: impl Into<Position>, rotation: impl Into<Rotation>, point: Vector ) -> bool

Tests whether the given point is inside of self transformed by translation and rotation.

source

pub fn cast_ray( &self, translation: impl Into<Position>, rotation: impl Into<Rotation>, ray_origin: Vector, ray_direction: Vector, max_time_of_impact: Scalar, solid: bool ) -> Option<(Scalar, Vector)>

Computes the time of impact and normal between the given ray and self transformed by translation and rotation.

The returned tuple is in the format (time_of_impact, normal).

§Arguments
  • ray_origin: Where the ray is cast from.
  • ray_direction: What direction the ray is cast in.
  • max_time_of_impact: The maximum distance that the ray can travel.
  • solid: If true and the ray origin is inside of a collider, the hit point will be the ray origin itself. Otherwise, the collider will be treated as hollow, and the hit point will be at the collider’s boundary.
source

pub fn intersects_ray( &self, translation: impl Into<Position>, rotation: impl Into<Rotation>, ray_origin: Vector, ray_direction: Vector, max_time_of_impact: Scalar ) -> bool

Tests whether the given ray intersects self transformed by translation and rotation.

§Arguments
  • ray_origin: Where the ray is cast from.
  • ray_direction: What direction the ray is cast in.
  • max_time_of_impact: The maximum distance that the ray can travel.
source

pub fn compound( shapes: Vec<(impl Into<Position>, impl Into<Rotation>, impl Into<Collider>)> ) -> Self

Creates a collider with a compound shape defined by a given vector of colliders with a position and a rotation.

Especially for dynamic rigid bodies, compound shape colliders should be preferred over triangle meshes and polylines, because convex shapes typically provide more reliable results.

If you want to create a compound shape from a 3D triangle mesh or 2D polyline, consider using the Collider::convex_decomposition method.

source

pub fn sphere(radius: Scalar) -> Self

Creates a collider with a sphere shape defined by its radius.

source

pub fn ball(radius: Scalar) -> Self

👎Deprecated since 0.4.0: please use Collider::sphere instead

Creates a collider with a ball shape defined by its radius.

source

pub fn cuboid(x_length: Scalar, y_length: Scalar, z_length: Scalar) -> Self

Creates a collider with a cuboid shape defined by its extents.

source

pub fn round_cuboid( x_length: Scalar, y_length: Scalar, z_length: Scalar, border_radius: Scalar ) -> Self

Creates a collider with a cuboid shape defined by its extents and rounded corners.

source

pub fn cylinder(height: Scalar, radius: Scalar) -> Self

Creates a collider with a cylinder shape defined by its height along the Y axis and its radius on the XZ plane.

source

pub fn cone(height: Scalar, radius: Scalar) -> Self

Creates a collider with a cone shape defined by its height along the Y axis and the radius of its base on the XZ plane.

source

pub fn capsule(height: Scalar, radius: Scalar) -> Self

Creates a collider with a capsule shape defined by its height along the Y axis and its radius.

source

pub fn capsule_endpoints(a: Vector, b: Vector, radius: Scalar) -> Self

Creates a collider with a capsule shape defined by its end points a and b and its radius.

source

pub fn halfspace(outward_normal: Vector) -> Self

Creates a collider with a half-space shape defined by the outward normal of its planar boundary.

source

pub fn segment(a: Vector, b: Vector) -> Self

Creates a collider with a segment shape defined by its endpoints a and b.

source

pub fn triangle(a: Vector, b: Vector, c: Vector) -> Self

Creates a collider with a triangle shape defined by its points a, b and c.

source

pub fn polyline(vertices: Vec<Vector>, indices: Option<Vec<[u32; 2]>>) -> Self

Creates a collider with a polyline shape defined by its vertices and optionally an index buffer.

source

pub fn trimesh(vertices: Vec<Vector>, indices: Vec<[u32; 3]>) -> Self

Creates a collider with a triangle mesh shape defined by its vertex and index buffers.

source

pub fn trimesh_with_config( vertices: Vec<Vector>, indices: Vec<[u32; 3]>, flags: TriMeshFlags ) -> Self

Creates a collider with a triangle mesh shape defined by its vertex and index buffers and flags controlling the preprocessing.

source

pub fn convex_decomposition( vertices: Vec<Vector>, indices: Vec<[u32; 3]> ) -> Self

Creates a collider shape with a compound shape obtained from the decomposition of a given trimesh defined by its vertex and index buffers.

source

pub fn convex_decomposition_with_config( vertices: Vec<Vector>, indices: Vec<[u32; 3]>, params: &VHACDParameters ) -> Self

Creates a collider shape with a compound shape obtained from the decomposition of a given trimesh defined by its vertex and index buffers. The given VHACDParameters are used for configuring the decomposition process.

source

pub fn convex_hull(points: Vec<Vector>) -> Option<Self>

Creates a collider with a convex polyhedron shape obtained after computing the convex hull of the given points.

source

pub fn heightfield(heights: Vec<Vec<Scalar>>, scale: Vector) -> Self

Creates a collider with a heightfield shape.

A 3D heightfield is a rectangle on the XZ plane, subdivided in a grid pattern at regular intervals.

heights is a matrix indicating the altitude of each subdivision point. The number of rows indicates the number of subdivisions along the X axis, while the number of columns indicates the number of subdivisions along the Z axis.

scale indicates the size of each rectangle on the XZ plane.

source

pub fn trimesh_from_mesh(mesh: &Mesh) -> Option<Self>

Creates a collider with a triangle mesh shape from a Mesh.

§Example
use bevy::prelude::*;
use bevy_xpbd_3d::prelude::*;

fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
    let mesh = Mesh::from(Cuboid::default());
    commands.spawn((
        Collider::trimesh_from_mesh(&mesh).unwrap(),
        PbrBundle {
            mesh: meshes.add(mesh),
            ..default()
        },
    ));
}
source

pub fn trimesh_from_mesh_with_config( mesh: &Mesh, flags: TriMeshFlags ) -> Option<Self>

Creates a collider with a triangle mesh shape from a Mesh using the given TriMeshFlags for controlling the preprocessing.

§Example
use bevy::prelude::*;
use bevy_xpbd_3d::prelude::*;

fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
    let mesh = Mesh::from(Cuboid::default());
    commands.spawn((
        Collider::trimesh_from_mesh_with_config(&mesh, TriMeshFlags::all()).unwrap(),
        PbrBundle {
            mesh: meshes.add(mesh),
            ..default()
        },
    ));
}
source

pub fn convex_hull_from_mesh(mesh: &Mesh) -> Option<Self>

Creates a collider with a convex polygon shape obtained from the convex hull of a Mesh.

§Example
use bevy::prelude::*;
use bevy_xpbd_3d::prelude::*;

fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
    let mesh = Mesh::from(Cuboid::default());
    commands.spawn((
        Collider::convex_hull_from_mesh(&mesh).unwrap(),
        PbrBundle {
            mesh: meshes.add(mesh),
            ..default()
        },
    ));
}
source

pub fn convex_decomposition_from_mesh(mesh: &Mesh) -> Option<Self>

Creates a compound shape obtained from the decomposition of a Mesh.

§Example
use bevy::prelude::*;
use bevy_xpbd_3d::prelude::*;

fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
    let mesh = Mesh::from(Cuboid::default());
    commands.spawn((
        Collider::convex_decomposition_from_mesh(&mesh).unwrap(),
        PbrBundle {
            mesh: meshes.add(mesh),
            ..default()
        },
    ));
}
source

pub fn convex_decomposition_from_mesh_with_config( mesh: &Mesh, parameters: &VHACDParameters ) -> Option<Self>

Creates a compound shape obtained from the decomposition of a Mesh with the given VHACDParameters passed to the decomposition algorithm.

§Example
use bevy::prelude::*;
use bevy_xpbd_3d::prelude::*;

fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
    let mesh = Mesh::from(Cuboid::default());
    let config = VHACDParameters {
        convex_hull_approximation: false,
        ..default()
    };
    commands.spawn((
        Collider::convex_decomposition_from_mesh_with_config(&mesh, &config).unwrap(),
        PbrBundle {
            mesh: meshes.add(mesh),
            ..default()
        },
    ));
}

Trait Implementations§

source§

impl AnyCollider for Collider

source§

fn aabb(&self, position: Vector, rotation: impl Into<Rotation>) -> ColliderAabb

Computes the Axis-Aligned Bounding Box of the collider with the given position and rotation.
source§

fn mass_properties(&self, density: Scalar) -> ColliderMassProperties

Computes the collider’s mass properties based on its shape and a given density.
source§

fn contact_manifolds( &self, other: &Self, position1: Vector, rotation1: impl Into<Rotation>, position2: Vector, rotation2: impl Into<Rotation>, prediction_distance: Scalar ) -> Vec<ContactManifold>

Computes all ContactManifolds between two colliders. Read more
source§

fn swept_aabb( &self, start_position: Vector, start_rotation: impl Into<Rotation>, end_position: Vector, end_rotation: impl Into<Rotation> ) -> ColliderAabb

Computes the swept Axis-Aligned Bounding Box of the collider. This corresponds to the space the shape would occupy if it moved from the given start position to the given end position.
source§

impl Clone for Collider

source§

fn clone(&self) -> Collider

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Component for Collider
where Self: Send + Sync + 'static,

§

type Storage = TableStorage

A marker type indicating the storage type used for this component. This must be either [TableStorage] or [SparseStorage].
source§

impl Debug for Collider

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Collider

source§

fn default() -> Self

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

impl From<SharedShape> for Collider

source§

fn from(value: SharedShape) -> Self

Converts to this type from the input type.
source§

impl<T: IntoCollider<Collider>> From<T> for Collider

source§

fn from(value: T) -> Self

Converts to this type from the input type.
source§

impl IntoCollider<Collider> for BoxedPolyline3d

source§

fn collider(&self) -> Collider

Creates a collider from self.
source§

impl IntoCollider<Collider> for Capsule3d

source§

fn collider(&self) -> Collider

Creates a collider from self.
source§

impl IntoCollider<Collider> for Cone

source§

fn collider(&self) -> Collider

Creates a collider from self.
source§

impl IntoCollider<Collider> for Cuboid

source§

fn collider(&self) -> Collider

Creates a collider from self.
source§

impl IntoCollider<Collider> for Cylinder

source§

fn collider(&self) -> Collider

Creates a collider from self.
source§

impl IntoCollider<Collider> for Line3d

source§

fn collider(&self) -> Collider

Creates a collider from self.
source§

impl IntoCollider<Collider> for Plane3d

source§

fn collider(&self) -> Collider

Creates a collider from self.
source§

impl<const N: usize> IntoCollider<Collider> for Polyline3d<N>

source§

fn collider(&self) -> Collider

Creates a collider from self.
source§

impl IntoCollider<Collider> for Segment3d

source§

fn collider(&self) -> Collider

Creates a collider from self.
source§

impl IntoCollider<Collider> for Sphere

source§

fn collider(&self) -> Collider

Creates a collider from self.
source§

impl ScalableCollider for Collider

source§

fn scale(&self) -> Vector

Returns the global scaling factor of the collider.
source§

fn set_scale(&mut self, scale: Vector, detail: u32)

Sets the global scaling factor of the collider. Read more
source§

fn scale_by(&mut self, factor: Vector, detail: u32)

Scales the collider by the given scaling factor. 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
§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U

Return the T [ShaderType] for self. When used in [AsBindGroup] derives, it is safe to assume that all images in self exist.
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
§

impl<C> Bundle for C
where C: Component,

§

fn component_ids( components: &mut Components, storages: &mut Storages, ids: &mut impl FnMut(ComponentId) )

§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>,

§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

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

§

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

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

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

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

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

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

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

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

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

§

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

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
§

impl<C> DynamicBundle for C
where C: Component,

§

fn get_components(self, func: &mut impl FnMut(StorageType, OwningPtr<'_>))

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FromWorld for T
where T: Default,

§

fn from_world(_world: &mut World) -> T

Creates Self using data from the given [World].
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
§

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

§

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

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

fn is_in_subset(&self) -> bool

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

fn to_subset_unchecked(&self) -> SS

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

fn from_subset(element: &SS) -> SP

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

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

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

§

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>,

§

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.
§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

§

fn clone_type_data(&self) -> Box<dyn TypeData>

§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> Settings for T
where T: 'static + Send + Sync,

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T
where T: WasmNotSend + WasmNotSync,

§

impl<T> WasmNotSync for T
where T: Sync,