melonJS
    Preparing search index...

    Class RapierAdapter

    melonJS physics adapter for Rapier 2D (https://rapier.rs), compiled to WebAssembly.

    Rapier is a fast rigid-body engine: many bodies at once, continuous collision detection per body, a deterministic simulation, joints and a character controller. This adapter implements the full PhysicsAdapter interface, so the same bodyDefs and collision hooks that run on the built-in, matter and planck adapters run here.

    Rapier's WebAssembly has to be compiled before an adapter can be constructed. RapierAdapter.create does both, and is the same call on every melonJS adapter; RapierAdapter.load compiles it ahead of time. Rapier works in meters and seconds; the adapter converts through RapierAdapterOptions.pixelsPerMeter (default 32).

    import { Application } from "melonjs";
    import { RapierAdapter } from "@melonjs/rapier2d-adapter";

    const app = new Application(800, 600, {
    parent: "screen",
    physic: await RapierAdapter.create({ gravity: { x: 0, y: 900 } }),
    });

    Implements

    Index
    capabilities: AdapterCapabilities = ...

    advertised capabilities; user code may branch on these

    gravity: Vector2d

    World gravity. Mutate to change at runtime. On an adapter whose bodies have depth (AdapterCapabilities.bodies3d) it may be a Vector3d, whose z pulls along the depth axis; a 2D adapter keeps a Vector2d.

    melonWorld: World

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

    name: "@melonjs/rapier2d-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: "rapier"

    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 (joints, the character controller, native queries).

    const adapter = app.world.adapter as RapierAdapter;
    const { rapier, world } = adapter;
    const a = player.body as RapierAdapter.Body;
    const b = anchor.body as RapierAdapter.Body;
    const params = rapier.JointData.revolute({ x: 0, y: 0 }, { x: 0, y: 0 });
    world.createImpulseJoint(params, a, b, true);

    Code that touches adapter.rapier or adapter.world is Rapier-only.

    url: "https://www.npmjs.com/package/@melonjs/rapier2d-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.

    world: World

    The Rapier world; exposed for advanced use. Created in init.

    • 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 RapierAdapter.Body

    • The body's collision shapes in renderable-local pixels, at the body's current position and rotation: one per Rapier collider, so what actually collides. An Ellipse is a circle of the average radius, a concave polygon is its triangles, and a shape with isActive: false has none.

      Parameters

      • renderable: Renderable

        the renderable whose body shapes to read

      Returns readonly BodyShape[]

    • 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 }

    • Portable velocity / force / position API. Every adapter implements these by routing to its native engine. Use these instead of mutating the body handle directly when writing adapter-agnostic code. They act on the live body, which a renderable has once it is in the world: call them from its onActivateEvent(), which runs after the body is built, or later, never from its constructor.

      Parameters

      Returns Vector2d

    • Whether Rapier has put the body to sleep: a dynamic body at rest, which it leaves out of the simulation until a contact, a force or a velocity wakes it. false for a static or kinematic body and for a renderable this adapter does not know.

      Parameters

      • renderable: Renderable

        the renderable whose body to read

      Returns boolean

      true while the body sleeps

    • 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

    • Copy physics-engine body positions back to renderable.pos and rotations to the renderable's transform. Called after step each frame. Adapters that mutate the renderable directly during step (e.g. BuiltinAdapter) may leave this a no-op.

      Returns void

    • Download and compile Rapier's WebAssembly. Every call returns the same promise, so it can be started early (in parallel with loader.preload()) and awaited wherever it is needed; a failed load (offline, a blocked chunk) rejects, and a later call tries again.

      Rapier is imported with import(), so bundlers put its 3 MB 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 = RapierAdapter.load();
      await loader.preload(assets);
      await rapierReady;
      app.world.setAdapter(new RapierAdapter());