Skip to content

Switching Physics Adapters

Olivier Biot edited this page Nov 13, 2026 · 15 revisions

Switching Physics Adapters

melonJS 19.5+ has a swappable physics layer. The built-in SAT physics is the default; rigid-body engines plug in through the same PhysicsAdapter interface: @melonjs/matter-adapter (matter-js), @melonjs/planck-adapter (a faithful Box2D 2.3.0 port), @melonjs/rapier2d-adapter (Rapier compiled to WebAssembly, melonJS 20.0+), or your own.

Per-renderable collision dispatch is normalized across every adapter. Every Renderable receives onCollisionStart / onCollisionActive / onCollisionEnd callbacks with a (response, other) signature β€” you write the same handlers no matter which engine is running underneath, and the adapter routes pair-level events to the right renderables for you.

This page covers what stays the same, what changes by design, and the porting pitfalls to watch for.

Prerequisite: this page assumes you're already on the 19.5 adapter API (declarative bodyDef, body method calls like body.setVelocity(x, y)). If your code still uses the legacy new me.Body(this, shape) pattern with direct body.vel / body.force mutation, migrate to bodyDef first β€” see Migrating to the Physics Adapter API. That migration is a one-time code-style refactor that stays on the built-in adapter; this page picks up from there to cover engine selection.

Picking an adapter

import { Application, BuiltinAdapter, video } from "melonjs";
import { MatterAdapter } from "@melonjs/matter-adapter";
import { PlanckAdapter } from "@melonjs/planck-adapter";
import { RapierAdapter } from "@melonjs/rapier2d-adapter";

const app = new Application(800, 600, {
    parent: "screen",
    renderer: video.AUTO,
    physic: await BuiltinAdapter.create(),   // default; same as omitting `physic`
    // physic: await MatterAdapter.create({ gravity: { x: 0, y: 5 } }),
    // physic: await PlanckAdapter.create({ gravity: { x: 0, y: 320 } }), // px/sΒ²
    // physic: await RapierAdapter.create({ gravity: { x: 0, y: 320 } }), // px/sΒ²
});
await app.init();   // mandatory since 20.0

physic takes an adapter, "builtin" (the default) or "none" (no physics: the world is a plain scene graph).

Make an adapter with await X.create(options) (melonJS 20.14+). Every adapter class has the same static pair: load() resolves once the adapter can be built, and create() waits for it, then constructs. The built-in, matter and planck adapters are plain JavaScript, so new X(options) still works for them, and is the form to use before 20.14. Rapier downloads and compiles its WebAssembly in load(), so make it with create(), or with new once await RapierAdapter.load() has resolved.

Which one? Stay on the built-in for platformers, top-down games, shoot-'em-ups and 2.5D with height. Move to an adapter when the game needs rotation that collides, stacking, joints, real friction or continuous collision. The physics skill has a table, game type by game type.

Switching while the game runs

Since melonJS 20.14, world.setAdapter() replaces the adapter of a running game, between two screens for example:

app.world.setAdapter(await PlanckAdapter.create({ gravity: { x: 0, y: 320 } }));
  • The old adapter loses every body, at any depth, and is destroyed (that frees Rapier's WebAssembly memory).
  • The new one builds every body again from its renderable's bodyDef, where the renderable stands and at the angle its body had (since 20.15; before, a turned body came back upright). The joints world.addJoint() made are built again too, after the bodies. Switching to an adapter without joints (built-in, matter) drops them and then throws, once the switch is complete: remove them first with world.removeJoint() (see Joints). Velocities, forces and contacts start again from rest. A body added with a direct adapter.addBody() call is not rebuilt, and a legacy Body without a bodyDef only works on the built-in adapter.
  • world.physic takes the new adapter's label ("builtin", "matter", "planck", "rapier"), and the console prints physics: <label>.
  • Called during a physics step, from a collision handler for example, the swap happens once that step ends. Called twice in one step, the last adapter wins.
  • A body the new adapter cannot build (a Box3d, Sphere or Point moving to a 2D engine) does not stop the swap: the other bodies move, and setAdapter() throws once afterwards, naming the first refusal (a deferred swap reports it with console.error).
  • world.adapter is read-only: assigning it throws. Use setAdapter().
  • Gravity, velocities and forces are in each adapter's own units: re-tune them (see below).

What stays the same

The PhysicsAdapter interface is the portable surface. Code written against these works on every adapter:

  • bodyDef (declarative body description on the renderable)
  • addBody / removeBody (auto-called by Container.addChild / removeChild)
  • getVelocity / setVelocity β€” read & write velocity
  • applyForce / applyImpulse β€” Newtonian force / impulse application
  • setPosition / setStatic / setGravityScale / setFrictionAir / setMaxVelocity
  • setCollisionType / setCollisionMask
  • setSensor β€” solid ⇄ pass-through toggle
  • isGrounded β€” standing on something (each adapter decides it a little differently, see below)
  • The four collision hooks on Renderable: onCollision, onCollisionStart, onCollisionActive, onCollisionEnd
  • The (response, other) signature of those hooks. The modern handlers (onCollisionStart / onCollisionActive / onCollisionEnd) share an identical core shape across every adapter ({ a, b, normal, depth, pair? }) β€” see Response shape below. The legacy onCollision gets the SAT-shaped response on the built-in adapter; on matter, planck and Rapier a renderable without onCollisionActive gets onCollision every frame of contact, with the modern response, and its return value is ignored.

If your gameplay code only touches the list above, it's portable across adapters.

Optional / capability-gated APIs

raycast(from, to) and queryAABB(rect) are portable across every adapter as of 19.5 β€” raycast is capability-gated via adapter.capabilities.raycasts (every official adapter returns true), and queryAABB is mandatory on the PhysicsAdapter interface. Both return the same shapes regardless of engine (RaycastHit = { renderable, point, normal, fraction }, queryAABB β†’ Renderable[]).

The remaining capability-gated methods:

Method Available on Notes
setAngle(r, angle) every adapter on the built-in the rotation is visual only: the sprite turns, its collision shapes do not
getMaxVelocity(r) every adapter capabilities.velocityLimit is true everywhere
querySphere(center, radius) / querySphere(sphere) builtin only (since 19.7) optional 3D sphere region query β€” the BuiltinAdapter's Octree broadphase implements both call shapes; matter, planck and Rapier omit the method. Narrow-phase is a centre-distance test against each candidate's getAbsolutePosition(). Call as world.adapter.querySphere?.(...) ?? [].
raycast3d(from, to) builtin only (since 19.7) optional 3D variant of raycast, capability-gated by capabilities.raycasts3d. BuiltinAdapter implements it via Octree.queryRay + per-candidate ray-vs-bounding-sphere narrow phase. matter, planck and Rapier declare raycasts3d: false and omit the method. Call as world.adapter.raycast3d?.(from, to) ?? null.

For optional features without a dedicated method, check the matching capabilities.<feature> flag:

Capability builtin matter planck Rapier
constraints (world.addJoint(), 20.15+) βœ— (addJoint() throws) βœ— (addJoint() throws; matter's own Matter.Constraint through adapter.matter) βœ“ βœ“
continuousCollisionDetection βœ— βœ— (matter-js has none: raise subSteps; matter-adapter < 1.6.0 reported βœ“) βœ“ (per-body bullet flag) βœ“ (per-body enableCcd)
sleepingBodies βœ— βœ“ βœ“ βœ“
raycasts βœ“ βœ“ βœ“ βœ“
raycasts3d (since 19.7) βœ“ βœ— βœ— βœ—
velocityLimit βœ“ βœ“ βœ“ βœ“
isGrounded βœ“ (the last step's push-out, see Quirks) βœ“ (contact-based) βœ“ (contact-based) βœ“ (contact-based)

Behavioural differences (by design)

These differences are expected and stem from each engine's design β€” they're documented here so you can plan around them, not because either one is wrong.

Also: see BuiltinAdapter Quirks for the list of SAT-only behaviors that work today but won't carry to other engines β€” patterns to avoid baking into code that might switch adapters later.

Behaviour Builtin (SAT) Matter Planck (Box2D) Rapier
setVelocity units px/step (added directly to pos each frame; dt-ignored) px/step (matter's Verlet; dt-ignored) px/s (integrated by dt; converted to m/s internally) px/s, as planck
applyForce units force.x is added directly to vel.x each frame (units = px/frameΒ²) force / mass * dtΒ² per step (Newtonian; small forces) Newtonian; force is in (pxΒ·kg)/sΒ², converted to m/sΒ² via pixelsPerMeter (x, y) / mass px/sΒ², acting for the whole frame across sub-steps
Default gravity 0.98 px/stepΒ², about 3600 px/sΒ² { x: 0, y: 1 }, about 900 px/sΒ² 320 px/sΒ² 320 px/sΒ²
Walking up a 45Β° slope Force-per-frame; even small WALK_FORCE climbs Newtonian; needs walk_force > mass * g * sin ΞΈ to overcome gravity-along-slope Same as matter Same as matter, or Rapier's character controller
Standing still on a slope ❌ no surface friction: a body slides down it βœ… surface friction βœ… βœ…
onCollision returning false to opt out of solid response βœ… honored ❌ ignored β€” the solver has already resolved separation by the time the hook fires; use setSensor instead ❌ ignored β€” same reason ❌ ignored β€” same reason
Body rotation under torque visual only: the sprite turns, its collision shapes never do βœ… unless fixedRotation: true (defaults to false since matter-adapter 1.4.0) βœ… unless fixedRotation: true (defaults to false since planck-adapter 1.5.0) βœ… unless fixedRotation: true (defaults to false)
kinematic bodies built as dynamic (falls under gravity) built as dynamic βœ… moved by their velocity βœ… moved by their velocity
One-way platforms return false from onCollision (SAT skips the response) setSensor(platform, true) + manual landing snap in onCollisionActive, or per-platform mask bits (the Matter Platformer example) Same as matter Same as matter
Slope handling Custom slope-hack pattern (response.overlapV.y = abs(overlap) to force upward push) Geometric β€” slopes must be authored as proper ramps; alternatively snap-to-surface in onCollisionActive Same as matter Same as matter, or Rapier's character controller
Continuous collision detection ❌ β€” fast objects can tunnel ❌ β€” matter-js has none: raise subSteps so a body moves less than its size per sub-step βœ… per-body bullet flag (Box2D's native CCD) βœ… per-body enableCcd(true)
Sleeping bodies ❌ βœ… βœ… βœ…
Joints through world.addJoint() (hinge, rope, weld, slider) ❌ ❌ βœ… βœ…
Engine-specific joints and constraints ❌ βœ… Matter.Constraint, via adapter.matter βœ… the rest of Box2D's joints, via adapter.planck βœ… Rapier's spring and the rest, via adapter.rapier
Default collisionType ENEMY_OBJECT PLAYER_OBJECT PLAYER_OBJECT PLAYER_OBJECT
Pausing a renderable with updateWhenPaused keeps moving the whole simulation stops the whole simulation stops the whole simulation stops
isGrounded the last step's push-out from below, with falling / jumping clear. See Quirks. a touching contact that pushes the body up (walls do not count) same as matter same as matter

Porting pitfalls

isGrounded is literal, not predictive

On matter, planck and Rapier it returns true while a touching contact pushes the body up: a floor or a slope, not the side of a wall (a contact with a sensor counts when the sensor's centre is below the body's). On the built-in adapter it reads the last step's push-out (see Quirks #11). Either way, inside an onCollisionStart handler for a stomp, the enemy you just landed on already counts as "ground" β€” so !isGrounded is not a reliable proxy for "I was airborne before this contact started."

Use the body's pre-contact velocity instead (vel.y > 0 = I was falling at the moment of contact).

Velocity units shift when switching to planck or Rapier β€” same call, different magnitude

setVelocity reads in px/step on builtin and matter (the value is added directly to position each frame; dt is ignored). On planck and Rapier it's px/second β€” the value is integrated over dt, so the same call moves the body ~60Γ— more slowly at 60fps. A setVelocity(0, 60) jump:

  • Builtin / matter: body moves 60 px in one step.
  • Planck, Rapier: body moves 60 px in one second (β‰ˆ 1 px / step at 60fps).

When porting a builtin or matter game to planck or Rapier, multiply impulse velocities by your frame rate (typically 60). Force-driven motion auto-scales because planck's applyForce is also dt-integrated; only the impulse-style setVelocity / applyImpulse calls need adjustment.

Matter forces are much smaller than builtin forces

If you tuned WALK_FORCE = 0.4 on the builtin adapter and switch to matter, the player will rocket sideways across the screen because force/mass * dtΒ² with dt β‰ˆ 16 and a typical 64Γ—96 sprite (mass β‰ˆ 6) gives a velocity contribution of ~30 per step. Most matter platformers use forces in the 0.01–0.05 range. Start two orders of magnitude smaller and tune up.

applyForce on matter is not a "one-shot impulse"

It's a sustained Newtonian force. matter resets body.force to zero at the end of each step, so the force only acts for one step β€” but that one step's contribution is force / mass * dtΒ², which depends on dt and the body's mass. For an instant velocity change (a jump, a dash, a knockback), use setVelocity or applyImpulse, not applyForce.

body.position is the centroid in matter; renderable.pos is top-left in melonJS

If your code reads body.position directly to put a UI marker over the body, the marker is offset by half the sprite's size. Either read renderable.pos (which the adapter keeps in sync), or compute body.position - posOffset where posOffset is half the sprite's extents.

Polylines (Line shapes) are 2px quads on matter and planck

Tiled emits a Line for every polyline. matter and planck have no segment primitive, so they simulate it as a thin quad, 2px across, following the segment (matter-adapter 1.5.0+, planck-adapter 1.6.0+; before that matter used the line's bounding box and planck a one-metre square). Rapier uses a true segment on a static or kinematic body, and the same thin quad on a dynamic one. A thin quad can be tunnelled by a fast-falling body, so give platforms some thickness at load time with adapter.updateShape(child, [new Rect(0, 0, w, thickness)]), as the Matter Platformer example does.

Response shape

The collision response shape depends on which handler family receives it:

Modern handlers (onCollisionStart / onCollisionActive / onCollisionEnd) β€” same contract on every adapter:

{
    a:      Renderable,             // always === this (the receiver)
    b:      Renderable,             // always === other (the partner)
    normal: { x: number, y: number }, // unit MTV for the receiver
    depth:  number,                 // penetration depth (always positive)
    pair?:  unknown,                // engine-native pair: Matter.Pair (matter), a planck Contact (planck), { collider1, collider2 } (Rapier); absent on builtin
    // builtin-only @deprecated SAT extras, flipped per receiver:
    overlap?:  number,
    overlapN?: { x, y },
    overlapV?: { x, y },
}

The portable stomp idiom is response.normal.y < -0.7 ("push me up to escape" β‡’ I'm on top of b). Same expression on every adapter. response.depth is the overlap in pixels on every adapter. response.pair is adapter-specific: reading it ties the handler to that engine.

Legacy onCollision handler β€” built-in SAT contract, unchanged from 19.4:

{
    a, b,                            // fixed per pair (NOT receiver-symmetric)
    overlap, overlapN, overlapV,     // SAT legacy fields, "from b β†’ a" sign
    aInB, bInA,
    indexShapeA, indexShapeB,
}

The legacy stomp idiom is response.overlapV.y > 0 && response.a === this (the response.a === this check is necessary because a/b are fixed per pair and the same handler fires once for each iteration order β€” see the BuiltinAdapter Quirks page).

On matter, planck and Rapier, onCollision receives the modern response above (no SAT fields) and its return value is ignored, so a handler written against overlapV needs porting.

A truly portable read

For "did I land on this?" / "was I falling at the moment of impact?" β€” both work, but if you want a single idiom that runs unchanged on every adapter and survives mid-tick velocity mutations:

onCollisionStart(_response, _other) {
    if (this.body.getVelocity().y > 0) {
        // I was falling at impact β€” same signal on every adapter
    }
}

Use the contact normal for direction-of-contact reads; use velocity for "what was I doing right before this contact" reads.

Collision filter / mask aliases

// All four assignments are equivalent β€” use whichever matches your background:
body.collisionType = collision.types.PLAYER_OBJECT;          // melonJS legacy
body.collisionFilter.category = collision.types.PLAYER_OBJECT; // matter-native

body.collisionMask = collision.types.ENEMY_OBJECT;
body.collisionFilter.mask = collision.types.ENEMY_OBJECT;

In @melonjs/matter-adapter, these are live getters/setters over the same underlying state β€” they can't drift. On planck and Rapier a body can carry several shapes, each with its own filter: body.collisionType / body.collisionMask read the first shape's values and write every shape's.

Recipes

Concrete patterns for common gameplay needs. Each recipe is labelled Portable (same renderable code under any adapter), Portable via velocity (same code, just route through the body's velocity rather than the contact response), or names the adapters it needs (a feature gated by adapter.capabilities).

Jump β€” instant upward impulse (Portable)

setVelocity is the canonical "impulse" pattern on every adapter. Direct mutation of vel.y works under the builtin adapter but not under matter (matter's Verlet integrator needs both velocity and positionPrev reset together); the body method handles that for you.

const vel = this.body.getVelocity();
this.body.setVelocity(vel.x, -JUMP_VEL);  // preserves horizontal motion

Trigger zone / coin pickup (Portable)

Mark the body as a sensor β€” collisions still fire onCollisionStart but the solver doesn't physically push the player away.

class Coin extends Sprite {
    constructor(x, y) {
        super(x, y, { image: "coin" });
        this.bodyDef = {
            type: "static",
            shapes: [new Ellipse(16, 16, 32, 32)],
            isSensor: true,
            collisionType: collision.types.COLLECTABLE_OBJECT,
            collisionMask: collision.types.PLAYER_OBJECT,
        };
    }
    onCollisionStart(_response, _other) {
        gameState.score += 100;
        this.ancestor.removeChild(this);
    }
}

One-way platform (Portable)

A sensor body + manual snap-to-top from the player. Falling players land; jumping players pass through; pressing down drops through.

// Platform definition
this.bodyDef = {
    type: "static",
    shapes: [new Rect(0, 0, width, height)],
    isSensor: true,        // <-- key: the solver doesn't try to resolve the contact
    collisionType: collision.types.WORLD_SHAPE,
    collisionMask: collision.types.PLAYER_OBJECT,
};

// Player handler β€” same on every adapter
onCollisionActive(_response, other) {
    if (other.type !== "platform") return;
    if (input.keyStatus("down")) return;              // drop-through
    const vel = this.body.getVelocity();
    if (vel.y < 0) return;                            // jumping up β€” pass through
    const playerBottom = this.pos.y + this.height;
    const platformTop = other.pos.y;
    if (playerBottom - platformTop > this.height * 0.5) return; // came from below
    const adapter = this.parentApp.world.adapter;
    adapter.setPosition(this, scratchPos.set(this.pos.x, platformTop - this.height));
    this.body.setVelocity(vel.x, 0);
}

Stomp detection (Portable via velocity)

Read the body's pre-contact velocity in onCollisionStart. The signal is identical on every adapter and survives mid-tick mutations that contact normals can't.

onCollisionStart(_response, other) {
    if (other.body.collisionType !== collision.types.ENEMY_OBJECT) return;
    const vel = this.body.getVelocity();
    if (vel.y > 0) {
        // I was falling at the moment of impact β€” stomp
        other.die();
        this.body.setVelocity(vel.x, -STOMP_BOUNCE);
    } else {
        this.hurt();
    }
}

response.normal and response.depth are portable too, if you want the contact's direction or how deep it is. Only response.pair is engine-native: a handler that reads it is tied to that engine (branch on app.world.physic if you must).

Joints: hinge, rope, weld, slider (Planck or Rapier)

Since melonJS 20.15, app.world.addJoint() joins two bodies the same way on the planck and Rapier adapters (capabilities.constraints is true), each building its engine's own joint. On the built-in and matter adapters it throws, naming the adapter: code meant to run on any adapter checks the flag first.

if (app.world.adapter.capabilities.constraints) {
    app.world.addJoint({ type: "rope", a: hook, b: lantern });
} else {
    // the built-in or matter adapter: hang the lantern some other way
}
// a door hinged at its top-left corner, opening up to 90 degrees
// (both renderables have a bodyDef and are already in the world)
const hinge = app.world.addJoint({
    type: "hinge",
    a: frame,
    b: door,
    anchorB: { x: 0, y: 0 },              // pixels, in the door's own space
    limits: { min: 0, max: Math.PI / 2 }, // b's angle minus a's
});

// a ball that swings on a rope, which can go slack
app.world.addJoint({ type: "rope", a: hook, b: ball, maxLength: 120 });

// a plank glued to a wall, that breaks off later
const glue = app.world.addJoint({ type: "weld", a: wall, b: plank });
app.world.removeJoint(glue);

// a lift that only moves up and down, at most 200 px above where it starts
app.world.addJoint({ type: "slider", a: shaft, b: cabin, axis: { x: 0, y: 1 }, limits: { min: -200, max: 0 } });
  • Anchors are in pixels, in each renderable's own space (its bodyDef shapes' space). anchorB defaults to the centre of b's body, and anchorA to the point of a under it, so a joint made without anchors holds the bodies where they stand; a rope joins the two centres.

  • The world keeps the joint: it is removed when either body leaves the world (moving it to another container of the same world, for its draw order, is not leaving), and built again by world.setAdapter() and by updateShape().

  • Moving to an adapter without joints, remove them first, or setAdapter() throws once the switch is complete (dropped N joints: the matter adapter has none):

    for (const joint of bridgeJoints) {
        app.world.removeJoint(joint);
    }
    app.world.setAdapter(await MatterAdapter.create());
  • addJoint() also throws, on planck and Rapier, for a renderable with no body in the world (add it with addChild() first) and for an unknown type.

  • A rope that collides is a chain of small bodies hinged end to end, with a rope joint from the first to the last so the chain cannot stretch: see the Ropes & Joints example.

  • On planck, a joint made or removed in a collision handler takes effect when the step ends. On Rapier, limits are soft: a fast body passes one by a few pixels for a frame.

Springs and engine-specific constraints (Matter, Planck or Rapier)

What addJoint() does not wrap is each engine's own API, reached through the adapter β€” no need to add the physics library as a direct dependency. The world does not keep these: they are not carried across setAdapter(), nor removed with their bodies.

Matter β€” Matter.Constraint:

const adapter = app.world.adapter as MatterAdapter;
const spring = adapter.matter.Constraint.create({
    bodyA: anchor.body as MatterAdapter.Body,
    bodyB: player.body as MatterAdapter.Body,
    stiffness: 0.04,    // 0 = floppy rope, 1 = rigid rod
    length: 80,
});
adapter.matter.Composite.add(adapter.engine.world, spring);

Use stiffness: 1 for a rigid hinge, low stiffness (~0.01–0.05) for spring-like behaviour.

Planck β€” the rest of Box2D's joints, here a spring:

const adapter = app.world.adapter as PlanckAdapter;
const anchorBody = anchor.body as PlanckAdapter.Body;
const playerBody = player.body as PlanckAdapter.Body;
const spring = adapter.world.createJoint(new adapter.planck.DistanceJoint(
    {
        length: 80 / adapter.pixelsPerMeter,  // planck wants meters
        frequencyHz: 4,                       // 0 = rigid, higher = stiffer
        dampingRatio: 0.5,
    },
    anchorBody,
    playerBody,
    anchorBody.getPosition(),             // world points, in meters
    playerBody.getPosition(),
));

Rapier β€” a spring, through adapter.rapier and adapter.world:

const adapter = app.world.adapter as RapierAdapter;
const { rapier, world } = adapter;

// rest length 2.5 m, stiffness 50, damping 1, at the bodies' centres (meters, body-local)
const params = rapier.JointData.spring(2.5, 50, 1, { x: 0, y: 0 }, { x: 0, y: 0 });
const spring = world.createImpulseJoint(
    params,
    anchor.body as RapierAdapter.Body,
    player.body as RapierAdapter.Body,
    true,
);

Rapier's objects live in WebAssembly memory: free a joint you created this way with world.removeImpulseJoint().

Each adapter's constraint solver runs inside its own step() β€” no extra integration code is needed in your update loop.

Sleeping bodies (Matter, Planck or Rapier)

These adapters can mark idle bodies as "sleeping" and skip integrating them entirely until disturbed β€” a meaningful CPU win when you have dozens of static-after-settling props (debris, fallen blocks, settled stacks).

Matter β€” enable at engine construction:

new MatterAdapter({
    gravity: { x: 0, y: 5 },
    matterEngineOptions: {
        enableSleeping: true,
    },
});

// Wake a specific body programmatically (e.g. on a trigger event):
const adapter = app.world.adapter as MatterAdapter;
if (adapter.capabilities.sleepingBodies) {
    adapter.matter.Sleeping.set(this.body, false);
}

Planck β€” sleeping is on per-body by default; just toggle the world flag if needed:

const adapter = app.world.adapter as PlanckAdapter;
adapter.world.setAllowSleeping(true);   // default β€” bodies sleep when idle

// Wake a specific body:
(this.body as planck.Body).setAwake(true);

Rapier β€” bodies sleep when they come to rest and wake on contact; body.sleep() and body.wakeUp() force it.

The builtin adapter has no equivalent β€” there's no integration cost to skip, since SAT only runs collisions, not Verlet integration.

A simple porting example

A minimal player entity. The same class on the built-in adapter, then ported to @melonjs/matter-adapter. Numbered comments call out what changed and why.

Before β€” built-in (SAT) adapter

import { Application, collision, input, Rect, Sprite, video } from "melonjs";

const app = new Application(800, 600, {
    parent: "screen",
    renderer: video.AUTO,
    // physic: defaults to BuiltinAdapter
});
await app.init();

const MAX_VEL_X = 3;
const MAX_VEL_Y = 15;

class Player extends Sprite {
    constructor(x: number, y: number) {
        super(x, y, { image: "player", framewidth: 64, frameheight: 96 });

        // declarative body β€” works on every adapter
        this.bodyDef = {
            type: "dynamic",
            shapes: [new Rect(0, 0, 64, 96)],
            collisionType: collision.types.PLAYER_OBJECT,
            maxVelocity: { x: MAX_VEL_X, y: MAX_VEL_Y },
            frictionAir: { x: 0.4, y: 0 },
        };

        input.bindKey(input.KEY.LEFT,  "left");
        input.bindKey(input.KEY.RIGHT, "right");
        input.bindKey(input.KEY.UP,    "jump", true);
    }

    update(dt: number) {
        const adapter = this.parentApp.world.adapter;
        const vel = adapter.getVelocity(this);

        // Horizontal: SAT integrates force.x directly into vel.x per frame.
        // A magnitude of MAX_VEL_X (=3) hits the velocity cap in one frame.
        if (input.isKeyPressed("left")) {
            adapter.applyForce(this, { x: -MAX_VEL_X, y: 0 });
        } else if (input.isKeyPressed("right")) {
            adapter.applyForce(this, { x:  MAX_VEL_X, y: 0 });
        }

        // Jump: edge-triggered. Set velocity directly upward.
        if (input.isKeyPressed("jump")) {
            adapter.setVelocity(this, { x: vel.x, y: -MAX_VEL_Y });
        }

        return super.update(dt);
    }

    onCollision(response, other) {
        if (other.body.collisionType !== collision.types.ENEMY_OBJECT) return true;
        // SAT idiom: "I came in from above" via overlapV.y > 0
        const adapter = this.parentApp.world.adapter;
        if (response.overlapV.y > 0 && !adapter.isGrounded(this)) {
            // stomp β€” bounce upward
            const vel = adapter.getVelocity(this);
            adapter.setVelocity(this, { x: vel.x, y: -MAX_VEL_Y * 0.75 });
            return false;
        }
        this.hurt();
        return false;
    }
}

After β€” @melonjs/matter-adapter

import { Application, collision, input, Rect, Sprite, video } from "melonjs";
import { MatterAdapter } from "@melonjs/matter-adapter";

const app = new Application(800, 600, {
    parent: "screen",
    renderer: video.AUTO,
    // (1) Swap the adapter. Pick a gravity that feels right for your sprite scale β€”
    //     matter's native (0, 1) is moon-like at 32px-arcade scale; ~5 is closer to
    //     legacy SAT feel. (`new MatterAdapter(...)` before melonJS 20.14.)
    physic: await MatterAdapter.create({ gravity: { x: 0, y: 5 } }),
});
await app.init();

const MAX_VEL_X = 3;
const MAX_VEL_Y = 15;

// (2) Matter forces are Newtonian (force/mass*dtΒ²). Magnitudes scale ~100Γ— smaller
//     than the SAT version β€” start here and tune.
const WALK_FORCE = 0.012;

class Player extends Sprite {
    constructor(x: number, y: number) {
        super(x, y, { image: "player", framewidth: 64, frameheight: 96 });

        // bodyDef is portable; same shape, same collision type, same maxVelocity cap.
        // (3) frictionAir is scalar in matter β€” averaging per-axis values would have
        //     surprised the Y axis with friction it didn't expect.
        this.bodyDef = {
            type: "dynamic",
            shapes: [new Rect(0, 0, 64, 96)],
            collisionType: collision.types.PLAYER_OBJECT,
            maxVelocity: { x: MAX_VEL_X, y: MAX_VEL_Y },
            frictionAir: 0.02,
        };

        input.bindKey(input.KEY.LEFT,  "left");
        input.bindKey(input.KEY.RIGHT, "right");
        input.bindKey(input.KEY.UP,    "jump", true);
    }

    update(dt: number) {
        const adapter = this.parentApp.world.adapter;
        const vel = adapter.getVelocity(this);

        // (4) Same applyForce calls β€” only the magnitude changed.
        if (input.isKeyPressed("left")) {
            adapter.applyForce(this, { x: -WALK_FORCE, y: 0 });
        } else if (input.isKeyPressed("right")) {
            adapter.applyForce(this, { x:  WALK_FORCE, y: 0 });
        }

        // (5) Jump: setVelocity is portable β€” instant velocity change works the same
        //     way on every adapter. No change needed.
        if (input.isKeyPressed("jump")) {
            adapter.setVelocity(this, { x: vel.x, y: -MAX_VEL_Y });
        }

        return super.update(dt);
    }

    // (6) Use onCollisionStart β€” fires exactly once per contact entry. The legacy
    //     `onCollision` alias still works on every adapter and fires every frame
    //     during contact; pick whichever cadence fits your handler logic.
    onCollisionStart(response, other) {
        if (other.body.collisionType !== collision.types.ENEMY_OBJECT) return;

        // (7) "Did I come in from above?" β€” replace `!isGrounded` (which flips to true
        //     the instant we land on the enemy) with the body's pre-contact velocity:
        //     vel.y > 0 means I was falling at the moment of impact. Position check
        //     guards against a falling side-swipe being counted as a stomp.
        const adapter = this.parentApp.world.adapter;
        const vel = adapter.getVelocity(this);
        if (vel.y > 0 && this.centerY < other.centerY) {
            adapter.setVelocity(this, { x: vel.x, y: -MAX_VEL_Y * 0.75 });
            return;
        }
        this.hurt();
        // (8) `return false` from `onCollision` to opt out of solid response is a SAT
        //     idiom β€” matter has already resolved the contact. Use
        //     adapter.setSensor(other, true) if you need non-solid behaviour.
    }
}

What changed, summarized

# Change Reason
1 Pass MatterAdapter to physic switching engines
2 WALK_FORCE = 0.012 (down from 3) matter forces are Newtonian β€” much smaller magnitudes
3 frictionAir: 0.02 (scalar, not {x, y}) matter has no per-axis air friction
4 applyForce call sites unchanged portable API
5 setVelocity for jump unchanged portable API; correct pattern for instant velocity change
6 onCollision β†’ onCollisionStart one-shot semantics fit a stomp/hurt event better than every-frame
7 Replace !isGrounded with vel.y > 0 + centerY < other.centerY isGrounded flips to true the instant we land
8 Drop return false from collision handler matter ignores the return value (solver has already run)

bodyDef shape, collision masks, max-velocity cap, key bindings, sprite setup β€” all unchanged.

Recommended porting checklist

  1. Boot banner β€” verify the console prints physics: <label> for your adapter (since 20.14 also after every setAdapter()).
  2. Gravity β€” each adapter has its own unit (see the table above). For matter, start with gravity: { x: 0, y: 4 } (matter-native default Γ— ~4) for arcade-feel platformers; planck and Rapier take px/sΒ². Tune from there.
  3. Forces β€” divide your existing builtin applyForce magnitudes by ~30–100 as a starting point.
  4. fixedRotation β€” pass fixedRotation: true in any bodyDef that should stay upright, such as a platformer actor: matter (1.4.0+), planck (1.5.0+) and Rapier default it to false, as the engines themselves do.
  5. One-way platforms / slopes β€” replace SAT-response hacks with setSensor + manual snap-to-surface in onCollisionActive.
  6. Stomp / "was I airborne" checks β€” replace !isGrounded with vel.y > 0 reads (the pre-contact velocity).
  7. TMX polylines β€” give platforms thickness at load time (see Polylines).
  8. Test β€” collision events fire as expected, no false hurts on stomp, no stuck-on-slope behaviour.

If you hit something that surprises you and isn't on this list, open an issue β€” it probably belongs here.

Clone this wiki locally