melonJS
    Preparing search index...

    Class Rapier3dAdapter

    melonJS physics adapter for Rapier 3D (https://rapier.rs), compiled to WebAssembly: rigid bodies that move and turn in three dimensions, for a game drawn with Camera3d.

    Bodies are declared as on every adapter, with a bodyDef, from the 3D shapes: Box3d, Sphere, Capsule3d, ConvexHull3d and TriangleMesh3d. Shapes are in the renderable's space, relative to its pos (and depth), which is where the body sits; each frame the body's position is written back to pos / depth, and its turn onto currentTransform, so a Mesh, a Sprite3d or a GLTFModel tumbles as it is simulated.

    The adapter takes the 3D form of the portable API: setVelocity, applyForce, applyImpulse and setPosition take a Vector3d, and getVelocity3d, getRotation / setRotation and getAngularVelocity3d read the rest. The 2D calls still work, in the plane of the body: a Vector2d leaves the depth as it was.

    Rapier's WebAssembly has to be compiled before an adapter can be constructed: Rapier3dAdapter.create does both.

    import { Application, Camera3d } from "melonjs";
    import { Rapier3dAdapter } from "@melonjs/rapier3d-adapter";

    const app = new Application(800, 600, {
    parent: "screen",
    cameraClass: Camera3d,
    physic: await Rapier3dAdapter.create(),
    });

    Implements

    Index
    capabilities: AdapterCapabilities = ...

    advertised capabilities; user code may branch on these

    gravity: Vector3d

    World gravity, in pixels per second². Change it at any time; read at every step.

    melonWorld: World

    Back-reference to the owning melonJS world (set in init).

    name: "@melonjs/rapier3d-adapter"

    Optional display name reported on the startup banner. Falls back to the adapter's physicLabel, then its class name — avoid relying on the latter, as it is mangled in minified builds. Third-party packages typically set this to their npm package id (e.g. "@melonjs/matter-adapter").

    physicLabel: "rapier3d"

    Short adapter identifier exposed as world.physic. User code uses it to branch on which physics implementation is active without importing the adapter class — e.g.

    if (app.world.physic === "matter") {
    // matter-only setup (constraints, etc.)
    }

    Convention: a single lowercase token. The first-party labels are "builtin" (default — BuiltinAdapter) and "matter" (@melonjs/matter-adapter). Third-party adapters should pick a concise identifier that won't collide with future official ones.

    The reserved value "none" is set on world.physic only when the user passes physic: "none" to Application to disable physics entirely; adapters should not use it.

    Defaults to "builtin" if an adapter doesn't declare its own — keeps legacy adapters wired in before this field was added still working.

    pixelsPerMeter: number

    Spatial conversion factor between melonJS pixels and Rapier meters.

    rapier: __module

    The Rapier module: an escape hatch for what the portable PhysicsAdapter interface does not cover (other joints, the character controller, native queries). See the README.

    url: "https://www.npmjs.com/package/@melonjs/rapier3d-adapter"

    Optional URL (npm / homepage / repo) reported on the startup banner. Convention matches the debug-plugin's startup line.

    version: string = __VERSION__

    Optional package version reported on the startup banner. Set this when shipping the adapter as a separate npm package so users can tell which version is wired in at a glance.

    • Register a body with the simulation. Returns an opaque handle that becomes renderable.body. Each adapter chooses its own concrete body type — see the class doc for the convention. Like the builtin Body constructor, it sets renderable.isKinematic to false, so the renderable takes part in physics and receives pointer events.

      Prefer the declarative path. Set renderable.bodyDef and call Container.addChild(renderable) — the container auto-invokes addBody AND inserts the renderable into the world's broadphase (QuadTree) in one atomic step. Direct calls to addBody only register the body with this adapter; they do NOT add the renderable to the world's container hierarchy, so the broadphase won't return it as a collision candidate. A body registered via direct addBody without a matching addChild will integrate (velocity, forces) but never collide.

      Parameters

      Returns Rapier3dAdapter.Body

    • Make a joint between two bodies: what world.addJoint() calls, which game code uses instead. A "hinge" is a Rapier revolute joint about axis (default Z), a "rope" a rope joint, a "weld" a fixed joint and a "slider" a prismatic joint along axis (default X). Anchors are in each renderable's own space, relative to its pos, in pixels, and the axis in a's; a z left out is 0.

      The bodies are joined as they stand, however each is turned: a weld and a slider keep the turn between them, and a hinge leaves them only the turn about its axis.

      Parameters

      Returns ImpulseJoint

      the Rapier joint

    • Read the body's current velocity cap (mirror of setMaxVelocity). Returns plain {x, y} so callers don't need to import a vector type. A body with no cap reports Infinity on both axes; a builtin Body always has one, 490 by default. Optional — adapters that don't implement velocity caps omit this method.

      Parameters

      Returns { x: number; y: number; z: number }

    • Whether Rapier has put the body to sleep: a dynamic body at rest, left out of the step until a contact or a write to it (a velocity, a force, an impulse, a position or a rotation, which all wake it) moves it again. false for a fixed or kinematic body, and for a renderable this adapter does not know, including every one once it is destroyed.

      Parameters

      • renderable: Renderable

        the renderable whose body to read

      Returns boolean

      true while the body sleeps

      // the shot is over once every block has come to rest
      const settled = blocks.every((b) => adapter.isSleeping(b));
    • Toggle a body between solid and sensor mode. A sensor still fires collision events (onCollisionStart / onCollisionActive / onCollisionEnd) but the engine does not push the bodies apart on contact — useful for one-way platforms, trigger zones, ground-snap ground assists, etc.

      Adapters without a native sensor flag emulate by toggling the collision mask between its previous value and NO_OBJECT.

      Parameters

      Returns void

    • Runtime body-property mutators. Each maps to the corresponding BodyDefinition field and lets game code change a body's physical properties without re-creating it. Adapter implementations route to their native engine (BuiltinAdapter writes to the Body handle; MatterAdapter calls Matter's Body.set* helpers). They act on the live body: what a body starts with goes in its BodyDefinition, and what is set on it from the start goes in the renderable's onActivateEvent(), which runs after the body is built, each time it enters the world.

      Parameters

      Returns void

    • Give a body new shapes. The body itself stays: its position, turn and velocities, its joints, what was changed on it at run time (static or not, gravity scale, damping, sensor, collision type and mask, bounce, speed cap, Rapier's own settings such as CCD) and the handle on renderable.body. Its colliders are replaced, so the pairs touching it end and start again, and its mass is that of the new shapes.

      A shape this adapter cannot build throws before anything is changed.

      Parameters

      • renderable: Renderable

        the body's renderable

      • shapes: BodyShape[]

        the new shapes, relative to pos

      Returns void

    • Download and compile Rapier's WebAssembly. Every call returns the same promise, so it can be started early and awaited wherever it is needed; a failed load rejects, and a later call tries again.

      Rapier is imported with import(), so bundlers put it in a chunk of its own, downloaded only when this is called.

      Returns Promise<void>

      a promise that resolves once the adapter can be constructed

      const rapierReady = Rapier3dAdapter.load();
      await loader.preload(assets);
      await rapierReady;
      app.world.setAdapter(new Rapier3dAdapter());