Rapier logo

UseRapier

Composable more advance physics world manipulation.

In order to provide more flexibility in more advance physic scenes, and similar to useTresContext we provide useRapier to access the physic world, internally is used by other components in this library.

Similar to useTres, useRapier can be only be used inside of a <physics /> since this component acts as the provider for the context data.

Usage

const { world, rapier, isDebug, isPaused, timeStep, timeScale, setWorld, step, onBeforeStep } = useRapier()

isDebug, isPaused, timeStep and timeScale are reactive refs synced from <Physics> props. They can be mutated at runtime:

const { isDebug, isPaused, timeScale, timeStep } = useRapier()

isDebug.value = true // Physics world in debug mode
isPaused.value = true // Pause the simulation
timeScale.value = 2 // Double speed
timeStep.value = 1 / 120 // Finer fixed steps

Gravity stays on the world itself and can be updated anytime:

const { world } = useRapier()
world.value.gravity.y = -20

onBeforeStep

onBeforeStep registers a callback invoked right before every world step (once per fixed substep) with the timestep about to be solved. Use it for logic that must run in lockstep with the solver, like applying forces or updating a DynamicRayCastVehicleController:

const { onBeforeStep } = useRapier()

onBeforeStep((timestep) => {
  vehicleController.updateVehicle(timestep)
})

The callback auto-unregisters when the component scope is disposed. It also returns an unregister function for manual cleanup:

const unregister = onBeforeStep(callback)
unregister()
With a fixed timeStep, the world can step zero or multiple times per rendered frame. Prefer onBeforeStep over useLoop's onBeforeRender for physics logic, otherwise forces desync from the simulation.
Please note that in the examples below use top level await. Make sure to wrap such code with a Vue's Suspense component.