Skip to main content

collider_creation_and_insertion

A collider is created by adding the Collider component. Other components like Transform, Sensor, Friction, etc. can be added to customize the collider.

info

The following example shows several initializations of components to customize collider being built. The input values are just random so using this example as-is will not lead to a useful result.

use bevy_rapier2d::prelude::*;

commands
.spawn(Collider::cuboid(1.0, 2.0))
.insert(Sensor)
.insert(TransformBundle::from(Transform::from_xyz(2.0, 0.0, 0.0)))
.insert(Friction::coefficient(0.7))
.insert(Restitution::coefficient(0.3))
.insert(ColliderMassProperties::Density(2.0));

A collider can optionally be attached to a rigid-body. Attaching a collider to a rigid-body will result in the rigid-body being affected by collisions. The collider's position will be automatically updated from the position of the rigid-body it is attached to. There are two ways of attaching a collider to a rigid-body. The second way allows you to attach multiple colliders to the same rigid-body:

  1. Attach the Collider to the same entity as the RigidBody.
  2. Attach the Collider to an entity that is a child of the entity containing the RigidBody.
// Attach a single collider to a rigid-body.
commands
.spawn(RigidBody::Dynamic)
.insert(Collider::ball(0.5));

// Attach a multiple colliders to a rigid-body.
commands
.spawn((RigidBody::Dynamic, GlobalTransform::default()))
.with_children(|children| {
children
.spawn(Collider::ball(0.5))
// Position the collider relative to the rigid-body.
.insert(TransformBundle::from(Transform::from_xyz(0.0, 0.0, -1.0)));
children
.spawn(Collider::ball(0.5))
// Position the collider relative to the rigid-body.
.insert(TransformBundle::from(Transform::from_xyz(0.0, 0.0, 1.0)));
});