Struct avian3d::collision::collider::Collider

source ·
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 radius and height
commands.spawn(Collider::capsule(0.5, 2.0));

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 avian3d::prelude::*;
use bevy::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, CollisionLayers, and CollisionMargin.

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

If you need to specify the shape of the collider statically, use ColliderConstructor and build your collider with the Collider::try_from_constructor method. This can also be done automatically by simply placing the ColliderConstructor on an entity.

Colliders can also be generated automatically for meshes and scenes. See ColliderConstructor and ColliderConstructorHierarchy.

§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 avian3d::prelude::*;
use bevy::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.

Collider is currently not Reflect. If you need to reflect it, you can use ColliderConstructor as a workaround.

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 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(radius: Scalar, height: Scalar) -> Self

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

source

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

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

source

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

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

source

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

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

source

pub fn half_space(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.

Note that the resulting collider will be hollow and have no interior. This makes it more prone to tunneling and other collision issues.

The CollisionMargin component can be used to add thickness to the shape if needed. For thin shapes like triangle meshes, it can help improve collision stability and performance.

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.

Note that the resulting collider will be hollow and have no interior. This makes it more prone to tunneling and other collision issues.

The CollisionMargin component can be used to add thickness to the shape if needed. For thin shapes like triangle meshes, it can help improve collision stability and performance.

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 controls the scaling factor along each axis.

source

pub fn try_from_constructor( collider_constructor: ColliderConstructor ) -> Option<Self>

Attempts to create a collider with the given ColliderConstructor. By using this, you can serialize and deserialize the collider’s creation method separately from the collider itself via the ColliderConstructor enum.

Returns None if creating the collider from the given ColliderConstructor failed.

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,

source§

const STORAGE_TYPE: StorageType = bevy::ecs::component::StorageType::Table

A constant indicating the storage type used for this component.
source§

fn register_component_hooks(_hooks: &mut ComponentHooks)

Called when registering this component, allowing mutable access to its ComponentHooks.
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
source§

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

source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> 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
source§

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

source§

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

source§

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

source§

fn get_component_ids( components: &Components, ids: &mut impl FnMut(Option<ComponentId>) )

Gets this Bundle’s component ids. This will be None if the component has not been registered.
source§

impl<T> Downcast<T> for T

source§

fn downcast(&self) -> &T

source§

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

source§

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

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

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

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

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

source§

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

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

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

source§

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.

source§

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

source§

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

Creates Self using data from the given World.
source§

impl<T> Instrument for T

source§

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

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

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.

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> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
source§

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

Initializes a with the given initializer. Read more
source§

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

Dereferences the given pointer. Read more
source§

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

Mutably dereferences the given pointer. Read more
source§

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

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

source§

impl<T> Upcast<T> for T

source§

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

source§

impl<T> WithSubscriber for T

source§

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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

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

source§

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

source§

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

source§

impl<T> WasmNotSendSync for T

source§

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