Bevy Rapier
repository·master·Indexed 23 days ago
https://github.com/dimforge/bevy_rapierHigh-performance 2D and 3D physics engines integrated as plugins for the Bevy game engine. It provides components for rigid body dynamics (Dynamic, Fixed, Kinematic), impulse and multibody joints, and a KinematicCharacterController for character movement. Features include continuous collision detection (CCD), soft-CCD, and tools for managing mass properties, external forces, and locked axes of motion.
What's inside bevy_rapier
- Bevy Rapier provides 2D and 3D physics engines specifically designed for the Bevy game engine. It is split into separate crates for 2D and 3D physics to allow users to choose the dimensionality required for their project.
Run bevy_rapier custom benchmarks
masterTo measure timings with detailed information using the standalone benchmark binary, run the
benchbinary in release mode. This binary executes different scene setups, gathers information, and outputs the results at the end.cargo run --release --bin benchRun short-lived statistical benchmarks with divan
masterFor short-lived benchmarks that rely on statistical analysis, use the
divanbench harness by runningcargo benchfor thebevy_rapier_benches3dpackage.cargo bench -p bevy_rapier_benches3dModify solver contacts for advanced physics effects
masterThe
modify_solver_contactshook inBevyPhysicsHooksprovides aContactModificationContextViewto manipulate how the constraints solver sees contacts. This is useful for:- Conveyor Belts: Setting the
surface_velocityof a solver contact. - Variable Materials: Modifying friction and restitution coefficients based on contact features.
- One-way Platforms: Modifying the contact normal.
- Disabling Contacts: Calling
context.solver_contacts.clear()to ignore all contacts in a manifold.
Each contact manifold also provides
context.user_data, au32that is persistent between timesteps as long as the manifold exists.- Conveyor Belts: Setting the
Use AsyncCollider for Mesh-based Colliders
masterWhen working with 3D meshes and the
async-colliderfeature, useAsyncColliderorAsyncSceneCollider. These components act as placeholders that will be replaced by actual collider shapes once the Bevy mesh assets are loaded and processed.ComputedColliderShape
Defines how the mesh should be converted into a collider:
TriMesh(TriMeshFlags): A triangle mesh.ConvexHull: A convex hull of the mesh.ConvexDecomposition(VHACDParameters): A convex decomposition (VHACD).
Configure Collider Scale
masterBy default,
Collideruses the scale from the entity'sGlobalTransform. You can override this behavior using theColliderScalecomponent:ColliderScale::Relative(Vect): Multiplies theGlobalTransformscale by this value.ColliderScale::Absolute(Vect): Replaces theGlobalTransformscale with this value.
Understand Rapier physics execution phases (PhysicsSet)
masterThe Rapier physics pipeline is organized into three main execution phases, represented by the
PhysicsSetenum. These sets ensure that data is synchronized between Bevy and the Rapier backend in the correct order:PhysicsSet::SyncBackend: Synchronizes and initializes backend data structures (like Rapier's internal rigid body sets) with current Bevy component state. This includes handling entity additions, removals, and transform changes.PhysicsSet::StepSimulation: Advances the actual physics simulation and updates the internal state for scene queries.PhysicsSet::Writeback: Writes the results of the simulation (e.g., new positions, velocities, and collision events) back into Bevy components andGlobalTransforms.
Understand TypedJoint and supported joint types
masterTypedJointis a wrapper enum that allows you to treat different specific joint types uniformly. It provides implementations forAsRef<GenericJoint>andAsMut<GenericJoint>, allowing you to access the underlyingGenericJointdata regardless of the specific joint type used.Supported joint types within
TypedJointinclude:FixedJointGenericJointPrismaticJointRevoluteJointRopeJointSpringJointSphericalJoint(available when thedim3feature is enabled)
Configure RigidBody types
masterThe
RigidBodycomponent determines how an entity interacts with the physics engine. Use the following variants:RigidBody::Dynamic: Affected by all external forces (gravity, impulses, etc.).RigidBody::Fixed: Cannot be affected by external forces; acts as a static object.RigidBody::KinematicPositionBased: Cannot be affected by external forces but can be controlled by the user via position. It provides one-way interaction (it can push dynamic bodies, but cannot be pushed by them).RigidBody::KinematicVelocityBased: Cannot be affected by external forces but can be controlled by the user via velocity. It also provides one-way interaction.
Note: A
RigidBody's trajectory is independent of any contacts or joints when using kinematic types.Manage RigidBody mass properties
masterTo manage the mass of a
RigidBody, use these components:AdditionalMassProperties: Use this to set additional mass.AdditionalMassProperties::Mass(f32): Adds a specific mass value to the body.AdditionalMassProperties::MassProperties(MassProperties): Adds custom mass, center of mass, and inertia.
ReadMassProperties: Use this to read the total mass properties (including contributions from attached colliders). Modifying this component does not affect the actual physics simulation; useAdditionalMassPropertiesinstead.
MassPropertiescontains:local_center_of_mass: The center of mass in local space.mass: The total mass.principal_inertia: The principal angular inertia (scalar in 2D,Vectin 3D).principal_inertia_local_frame: The principal vectors of the local angular inertia tensor (3D only).
Configure the physics simulation timestep with TimestepMode
masterThe
TimestepModeresource determines how the physics simulation advances in time relative to Bevy's ticks. You can choose between three modes:Fixed: The simulation advances by a constantdtseconds at every Bevy tick, divided into a specific number ofsubsteps. This provides highly predictable physics behavior.Variable: The simulation advances by a variable amount based on the elapsed time, capped bymax_dt. You can usetime_scaleto implement slow-motion (< 1.0) or fast-forward (> 1.0) effects.Interpolated: Uses a fixeddtbut only steps the simulation if the physics time is behind the real-world elapsed time (adjusted bytime_scale). For smooth visuals, attach theTransformInterpolationcomponent to rigid bodies to estimate positions between steps.
By default,
TimestepModeusesVariablewith amax_dtof 1/60s, atime_scaleof 1.0, and 1 substep.How SpringJoint behaves numerically
masterA
SpringJointis integrated implicitly. This means that even an undamped spring will be subject to some amount of numerical damping and will eventually come to rest.To achieve more realistic results and reduce the effect of numerical damping, you should:
- Increase the number of solver iterations.
- Use smaller timesteps.