@dandre3000/rapier3d-sandbox
v0.1.0
Published
Rapier3D physics in a worker sandbox.
Maintainers
Readme
@dandre3000/rapier3d-sandbox
Rapier3D physics in a worker sandbox.
Install
npm i @dandre3000/rapier3d-sandbox
Usage
import { Rapier3DSandbox } from '@dandre3000/rapier3d-sandbox'
const sandbox = new Rapier3DSandbox
const physics = async () => {
/** @type {import("@dandre3000/rapier3d-sandbox").Rapier3DSandboxContext} */
const { rapier } = globalThis
await rapier.init()
let gravity = { x: 0.0, y: -9.81, z: 0.0 }
let world = new rapier.World(gravity)
// Create the ground
let groundColliderDesc = rapier.ColliderDesc.cuboid(10.0, 0.1, 10.0)
world.createCollider(groundColliderDesc)
// Create a dynamic rigid-body.
let rigidBodyDesc = rapier.RigidBodyDesc.dynamic()
.setTranslation(0.0, 1.0, 0.0)
let rigidBody = world.createRigidBody(rigidBodyDesc)
// Create a cuboid collider attached to the dynamic rigidBody.
let colliderDesc = rapier.ColliderDesc.cuboid(0.5, 0.5, 0.5)
let collider = world.createCollider(colliderDesc, rigidBody)
globalThis.rigidBody = rigidBody
globalThis.world = world
}
const step = () => {
// Step the simulation forward.
world.step()
// Get and print the rigid-body's position.
let position = rigidBody.translation()
console.log("Rigid-body position: ", position.x, position.y)
}
sandbox.setRemoteFunction('physics', physics)
sandbox.setRemoteFunction('step', step)
await sandbox.callRemoteFunction('physics')
setInterval(() => {
sandbox.callRemoteFunction('step')
}, 16)Exports
Class Rapier3DSandbox
setLocalFunction (id: string, fn: Function | null): void
Create sandboxed function on the main thread or remove it if fn is null.
setRemoteFunction (id: string, fn: Function | null): Promise<void>
Create a sandboxed function on the physics thread or remove it if fn is null.
callRemoteFunction (id: string): Promise<void>
Call a sandboxed function on the physics thread.
