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
- Rigid bodies
- Density
- Friction and restitution (bounciness)
- Collision layers
- Sensors
- Collision margins for adding extra thickness to colliders
- Generating colliders for meshes and scenes with
ColliderConstructor
andColliderConstructorHierarchy
- Get colliding entities
- Collision events
- Accessing, filtering and modifying collisions
- Manual contact queries
§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
impl Collider
sourcepub fn shape(&self) -> &SharedShape
pub fn shape(&self) -> &SharedShape
Returns the raw unscaled shape of the collider.
sourcepub fn shape_scaled(&self) -> &SharedShape
pub fn shape_scaled(&self) -> &SharedShape
Returns the shape of the collider with the scale from its GlobalTransform
applied.
sourcepub fn set_shape(&mut self, shape: SharedShape)
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.
sourcepub fn set_scale(&mut self, scale: Vector, num_subdivisions: u32)
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.
sourcepub fn project_point(
&self,
translation: impl Into<Position>,
rotation: impl Into<Rotation>,
point: Vector,
solid: bool
) -> (Vector, bool)
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.
sourcepub fn distance_to_point(
&self,
translation: impl Into<Position>,
rotation: impl Into<Rotation>,
point: Vector,
solid: bool
) -> Scalar
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.
sourcepub fn contains_point(
&self,
translation: impl Into<Position>,
rotation: impl Into<Rotation>,
point: Vector
) -> bool
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
.
sourcepub 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)>
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.
sourcepub fn intersects_ray(
&self,
translation: impl Into<Position>,
rotation: impl Into<Rotation>,
ray_origin: Vector,
ray_direction: Vector,
max_time_of_impact: Scalar
) -> bool
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.
sourcepub fn compound(
shapes: Vec<(impl Into<Position>, impl Into<Rotation>, impl Into<Collider>)>
) -> Self
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.
sourcepub fn sphere(radius: Scalar) -> Self
pub fn sphere(radius: Scalar) -> Self
Creates a collider with a sphere shape defined by its radius.
sourcepub fn cuboid(x_length: Scalar, y_length: Scalar, z_length: Scalar) -> Self
pub fn cuboid(x_length: Scalar, y_length: Scalar, z_length: Scalar) -> Self
Creates a collider with a cuboid shape defined by its extents.
sourcepub fn round_cuboid(
x_length: Scalar,
y_length: Scalar,
z_length: Scalar,
border_radius: Scalar
) -> Self
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.
sourcepub fn cylinder(radius: Scalar, height: Scalar) -> Self
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.
sourcepub fn cone(radius: Scalar, height: Scalar) -> Self
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.
sourcepub fn capsule(radius: Scalar, length: Scalar) -> Self
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.
sourcepub fn capsule_endpoints(radius: Scalar, a: Vector, b: Vector) -> Self
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
.
sourcepub fn half_space(outward_normal: Vector) -> Self
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.
sourcepub fn segment(a: Vector, b: Vector) -> Self
pub fn segment(a: Vector, b: Vector) -> Self
Creates a collider with a segment shape defined by its endpoints a
and b
.
sourcepub fn triangle(a: Vector, b: Vector, c: Vector) -> Self
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
.
sourcepub fn polyline(vertices: Vec<Vector>, indices: Option<Vec<[u32; 2]>>) -> Self
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.
sourcepub fn trimesh(vertices: Vec<Vector>, indices: Vec<[u32; 3]>) -> Self
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.
sourcepub fn trimesh_with_config(
vertices: Vec<Vector>,
indices: Vec<[u32; 3]>,
flags: TrimeshFlags
) -> Self
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.
sourcepub fn convex_decomposition(
vertices: Vec<Vector>,
indices: Vec<[u32; 3]>
) -> Self
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.
sourcepub fn convex_decomposition_with_config(
vertices: Vec<Vector>,
indices: Vec<[u32; 3]>,
params: VhacdParameters
) -> Self
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.
sourcepub fn convex_hull(points: Vec<Vector>) -> Option<Self>
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.
sourcepub fn heightfield(heights: Vec<Vec<Scalar>>, scale: Vector) -> Self
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.
sourcepub fn try_from_constructor(
collider_constructor: ColliderConstructor
) -> Option<Self>
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
impl AnyCollider for Collider
source§fn aabb(&self, position: Vector, rotation: impl Into<Rotation>) -> ColliderAabb
fn aabb(&self, position: Vector, rotation: impl Into<Rotation>) -> ColliderAabb
source§fn mass_properties(&self, density: Scalar) -> ColliderMassProperties
fn mass_properties(&self, density: Scalar) -> ColliderMassProperties
source§fn contact_manifolds(
&self,
other: &Self,
position1: Vector,
rotation1: impl Into<Rotation>,
position2: Vector,
rotation2: impl Into<Rotation>,
prediction_distance: Scalar
) -> Vec<ContactManifold>
fn contact_manifolds( &self, other: &Self, position1: Vector, rotation1: impl Into<Rotation>, position2: Vector, rotation2: impl Into<Rotation>, prediction_distance: Scalar ) -> Vec<ContactManifold>
ContactManifold
s between two colliders. Read moresource§fn swept_aabb(
&self,
start_position: Vector,
start_rotation: impl Into<Rotation>,
end_position: Vector,
end_rotation: impl Into<Rotation>
) -> ColliderAabb
fn swept_aabb( &self, start_position: Vector, start_rotation: impl Into<Rotation>, end_position: Vector, end_rotation: impl Into<Rotation> ) -> ColliderAabb
source§impl Component for Collider
impl Component for Collider
source§const STORAGE_TYPE: StorageType = bevy::ecs::component::StorageType::Table
const STORAGE_TYPE: StorageType = bevy::ecs::component::StorageType::Table
source§fn register_component_hooks(_hooks: &mut ComponentHooks)
fn register_component_hooks(_hooks: &mut ComponentHooks)
ComponentHooks
.source§fn from(value: SharedShape) -> Self
fn from(value: SharedShape) -> Self
source§impl IntoCollider<Collider> for BoxedPolyline3d
impl IntoCollider<Collider> for BoxedPolyline3d
source§impl IntoCollider<Collider> for Capsule3d
impl IntoCollider<Collider> for Capsule3d
source§impl IntoCollider<Collider> for Cone
impl IntoCollider<Collider> for Cone
source§impl IntoCollider<Collider> for Cuboid
impl IntoCollider<Collider> for Cuboid
source§impl IntoCollider<Collider> for Cylinder
impl IntoCollider<Collider> for Cylinder
source§impl IntoCollider<Collider> for Line3d
impl IntoCollider<Collider> for Line3d
source§impl IntoCollider<Collider> for Plane3d
impl IntoCollider<Collider> for Plane3d
source§impl<const N: usize> IntoCollider<Collider> for Polyline3d<N>
impl<const N: usize> IntoCollider<Collider> for Polyline3d<N>
source§impl IntoCollider<Collider> for Segment3d
impl IntoCollider<Collider> for Segment3d
source§impl IntoCollider<Collider> for Sphere
impl IntoCollider<Collider> for Sphere
Auto Trait Implementations§
impl Freeze for Collider
impl !RefUnwindSafe for Collider
impl Send for Collider
impl Sync for Collider
impl Unpin for Collider
impl !UnwindSafe for Collider
Blanket Implementations§
source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<C> Bundle for Cwhere
C: Component,
impl<C> Bundle for Cwhere
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
source§fn get_component_ids(
components: &Components,
ids: &mut impl FnMut(Option<ComponentId>)
)
fn get_component_ids( components: &Components, ids: &mut impl FnMut(Option<ComponentId>) )
source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
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>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
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)
fn as_any(&self) -> &(dyn Any + 'static)
&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)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&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
impl<T> DowncastSync for T
source§impl<C> DynamicBundle for Cwhere
C: Component,
impl<C> DynamicBundle for Cwhere
C: Component,
fn get_components(self, func: &mut impl FnMut(StorageType, OwningPtr<'_>))
source§impl<T> FromWorld for Twhere
T: Default,
impl<T> FromWorld for Twhere
T: Default,
source§fn from_world(_world: &mut World) -> T
fn from_world(_world: &mut World) -> T
Self
using data from the given World
.source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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 moresource§impl<T> Pointable for T
impl<T> Pointable for T
source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self
from the equivalent element of its
superset. Read moresource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self
is actually part of its subset T
(and can be converted to it).source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset
but without any property checks. Always succeeds.source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self
to the equivalent element of its superset.