Skip to main content

Common mistakes

My local build of Rapier is slower than the online demos​

Make sure the bindings are built in release mode. Rapier can be 100 times slower without optimizations enabled. The package installed by pip is always optimized, but the bindings built from source are only optimized if --release is given to maturin, e.g., maturin develop --release -m bindings/python/rapier-py-3d/Cargo.toml (see building from source). The build mode of the bindings actually loaded by your application is given by the profile property of rapier3d.build_features():

# A debug build of the bindings is up to 100 times slower.
if rp.build_features().profile != "release":
print("Warning: the rapier3d bindings are built without optimizations.")

Keep in mind as well that each call from Python to the bindings has a cost: a script calling a method of every rigid-body at each frame may spend more time in Python than in the simulation itself. For example, iterate only on the rigid-bodies that moved during the last timestep (see the island manager) rather than on all of them.

Rigid-body isn't affected by gravity​

If you expect your rigid-body to fall because of gravity but it doesn't, please make sure to double-check the following:

  • Your gravity vector is non-zero.
  • Your rigid-body is a dynamic rigid-body.
  • You didn't lock the translations of the rigid-body.
  • The rigid-body has a non-zero mass.

Note that a collider not attached to a dynamic rigid-body will never fall because it won't be affected by forces.

note

If the rigid-body has no collider attached to it, its mass will be zero unless you gave it a mass (or mass properties) explicitly. If the rigid-body has colliders attached to it and you didn't give the rigid-body a mass explicitly, make sure that at least one of the colliders has a non-zero density (or non-zero mass if you set it explicitly on the collider).

warning

The shapes that don't enclose any volume, i.e., the polylines, the half-spaces, the segments, and the triangles in 3D, have a zero mass whatever their density. So if a rigid-body only has colliders with such shapes attached to it, you need to set its mass/angular inertia manually. Note that a triangle-mesh isn't one of them: its mass properties are computed from the volume enclosed by its faces, which assumes that the mesh is closed and that its triangles are consistently oriented.

warning

A PhysicsWorld created without its gravity argument, e.g., PhysicsWorld(), has no gravity at all. Give it explicitly, e.g., PhysicsWorld(gravity=(0.0, -9.81, 0.0)), or set its gravity property afterwards.

Applying a force to a rigid-body doesn't work​

If applying a force or an impulse to a rigid-body doesn't work, please make sure to double-check the following:

  • The rigid-body is a dynamic rigid-body.
  • The rigid-body has a non-zero mass (or non-zero angular inertia for torques).
  • The force or impulse must be strong enough to actually push the rigid-body. You may for example try with a very high force/impulse value (say, with a magnitude of 100_000.0) and see if this stronger force works.
  • The rigid-body is awake, either by calling RigidBody.wake_up() explicitly, or by keeping the wake_up argument of the force/impulse application method to True (its default value).
  • The force is applied to the rigid-body of the world, i.e., to the view given by world.rigid_bodies[handle], rather than to a RigidBody built by your code before its insertion (see below).
note

If the rigid-body has no collider attached to it, its mass will be zero unless you gave it a mass (or mass properties) explicitly. If the rigid-body has colliders attached to it and you didn't give the rigid-body a mass explicitly, make sure that at least one of the colliders has a non-zero density (or non-zero mass if you set it explicitly on the collider).

A rigid-body suddenly stops being simulated​

It may happen that a rigid-body disappears from the simulation, i.e., it stops moving and stops generating contacts, without being removed by your own code. This generally means that non-finite values (NaN or infinites) appeared in its position or in its velocity for one reason or another (could be the simulation diverged, incorrect values provided, etc.)

Rather than crashing or letting these values propagate and corrupt the whole simulation, Rapier detects them at the beginning and at the end of each timestep, and puts the affected rigid-body, collider, or soft-body in quarantine: it is reset to its last valid position when one is known, its velocities are zeroed, and it is disabled.

The quarantined objects of the last timestep are reported by the PhysicsWorld.quarantine property (or by PhysicsPipeline.quarantine if you step the pipeline yourself), which lists their handles in its bodies, colliders, and soft_bodies properties. This report is cleared at each timestep, so it must be read after the step that generated it. Once the cause is fixed, a quarantined object is brought back into the simulation by setting its is_enabled property to True:

world.step()

# After the step, the objects neutralized by this step are known.
for handle in world.quarantine.bodies:
print(f"The rigid-body {handle} went non-finite and was disabled.")
# Once the cause is fixed, the rigid-body is brought back into the simulation.
world.rigid_bodies[handle].is_enabled = True

The most common configuration that leads to non-finite values is two dynamic rigid-bodies with a zero mass starting to be in contact. Therefore, make sure that your dynamic rigid-bodies have a non-zero mass. Note that the values given to the physics engine are checked too: a position or a velocity set to NaN by your own code (e.g. after a division by a zero-length vector) is caught at the beginning of the next timestep.

note

If the rigid-body has no collider attached to it, its mass will be zero unless you gave it a mass (or mass properties) explicitly. If the rigid-body has colliders attached to it and you didn't give the rigid-body a mass explicitly, make sure that at least one of the colliders has a non-zero density (or non-zero mass if you set it explicitly on the collider).

Why is everything moving in slow-motion?​

A common mistake, especially in 2D, is to use pixels as the length unit in the physics world. Let's say that in 2D you have a 100x100 pixels sprite for your player. It may be tempting to use a 100x100 cuboid collider for this sprite: Collider.cuboid(50.0, 50.0, 50.0) (we set 50.0 because this is the half-width of the cuboid). Doing this will make it look like the simulation runs in slow-motion because the cuboid will be huge compared to the magnitude of the usual gravity (-9.81).

The recommended way of using Rapier is to use SI units (meters, seconds, kilograms, etc.) If the player sprite is a 100x100 cuboid, then it is as if your player is 100 meters tall and 100 meters wide, which is huge. Therefore it is recommended to have a scaling factor between the graphics and the physics. For example we can say that 1 physics meter is equal to 50 pixels. This means that we can initialize our player collider as a 2x2 cuboid while still using a 100x100 pixels sprite.

All we need to do to keep measures in sync is to multiply by our scaling factor 50 all the positions given by the physics engine before rendering:

PIXELS_PER_METER = 50.0
# Scale the translation to convert from meters to pixels.
sprite_translation = ball.translation * PIXELS_PER_METER
# Rotations don't need to be scaled.
sprite_rotation = ball.rotation

The Python bindings being 3D only, this generally happens with the units of the renderer or of the 3D modeling tool the scene comes from (e.g. centimeters). Alternatively, the length unit of the simulation can be set to the number of your units that make one meter with the length_unit property of the IntegrationParameters, which scales the internal tolerances of Rapier accordingly. However, every value given to the engine (sizes, positions, velocities, and the gravity) must then be expressed in your own units.

My modifications have no effect​

Indexing a set of the world with a handle, e.g., world.rigid_bodies[handle], gives a live view of the object stored in the world: modifying it modifies the simulation. However, the other objects given by the bindings are generally copies, and modifying them has no effect on the world:

  • Some structures given by the properties of another object, e.g., the contact_softness of the IntegrationParameters, are copies which must be assigned back to their property once modified (the docstring of each property tells whether it gives a copy or a live view).
  • A rigid-body or a collider built by your code (e.g. with RigidBody.dynamic().build()) is copied into the set it is inserted into: once inserted, it must be modified through the view given by the set, not through the object you built.
  • The vectors, points, and rotations (e.g. Vec3) are immutable: body.translation.y = 2.0 raises an AttributeError, so a whole new value must be given to the property instead, e.g., body.translation = (0.0, 2.0, 0.0).
# The structures given by the properties of the integration parameters are copies.
params = world.integration_parameters
softness = params.contact_softness
softness.natural_frequency = 60.0 # Modifies the copy only.
params.contact_softness = softness # Applies the modification.

# A rigid-body (or a collider) inserted into a set is copied into the set as well.
body = rp.RigidBody.dynamic(translation=(0.0, 3.0, 0.0)).build()
handle = world.rigid_bodies.insert(body)
body.linvel = (1.0, 0.0, 0.0) # No effect on the rigid-body of the world.
world.rigid_bodies[handle].linvel = (1.0, 0.0, 0.0) # Modifies the rigid-body of the world.

# The vectors are immutable: a whole new vector is given instead.
world.rigid_bodies[handle].translation = (0.0, 4.0, 0.0)

An exception is raised by PhysicsWorld.step​

The exceptions raised by your physics hooks or by your event handler don't interrupt the timestep calling them: the first one is raised again by PhysicsWorld.step once the timestep is complete (by PhysicsPipeline.step if you step the pipeline yourself), which is where it can be caught. Set PhysicsWorld.event_error_policy to "strict" to skip the calls to the other callbacks of the timestep once one of them failed:

class Hooks:
def modify_solver_contacts(self, context):
raise ValueError("Something went wrong in the hook.")


world.physics_hooks = Hooks()
try:
world.step()
except ValueError as error:
# Raised once the timestep is complete.
print("The hook failed:", error)

Keep in mind that the world is being modified while these callbacks are called: they can read the world (e.g. through the colliders and bodies properties of the context they are given), but modifying it raises a RuntimeError. The modifications they need are recorded, e.g., in the attributes of the hooks, and applied once the timestep is complete:

class GroundContacts:
def __init__(self):
# The handles of the rigid-bodies touching the ground, recorded during the timestep.
self.bodies_to_push = []

def modify_solver_contacts(self, context):
# The world can be read here, but not modified: only record what must be done.
other_body = context.rigid_body2 if context.collider1 == ground else context.rigid_body1
if other_body is not None:
self.bodies_to_push.append(other_body)


hooks = GroundContacts()
world.physics_hooks = hooks
world.step()

# The world can be modified once the timestep is complete.
for body_handle in hooks.bodies_to_push:
world.rigid_bodies[body_handle].apply_impulse((0.0, 0.1, 0.0))
hooks.bodies_to_push.clear()

A RuntimeError is raised while the world is stepped​

A world can't be modified while it is being stepped. A modification of the world, or of one of its structures, raises a RuntimeError when:

  • It is done by a physics hook or an event handler during the timestep (see above).
  • Another thread is stepping the world at the same time (in this case, reading the world raises this error as well). A world can be used from any thread, but not from several threads at once: synchronize these threads (e.g. with a threading.Lock), or give each of them its own world (see threads and the GIL).

An InvalidHandle exception is raised​

The handle of an object becomes stale as soon as its object is removed from the world: indexing a set with a stale handle raises an InvalidHandle exception, and so does using a view obtained before the removal. Note that removing a rigid-body also removes the joints attached to it, and its colliders, so their handles become stale as well. If an object may have been removed by another part of your application, check its handle first with the in operator, e.g., handle in world.rigid_bodies, or use the get method of the set which returns None instead (see handles).