melonJS
    Preparing search index...

    Interface PhysicsAdapter

    Swappable physics engine integration. BuiltinAdapter ships with melonjs and wraps the engine's native SAT-based physics; third-party adapters (e.g. @melonjs/matter-adapter) implement this interface to plug a different engine in.

    Lifecycle contract: one adapter per World at a time, passed to Application at construction or swapped in later with World#setAdapter. A swap rebuilds every body from its bodyDef and every joint from its JointDefinition; the rest of an adapter's state (velocities, contacts, sleeping flags) does not carry over.

    Body handle convention: PhysicsAdapter.addBody returns an opaque handle that becomes renderable.body. Each adapter chooses its own concrete body type — BuiltinAdapter returns the legacy Body class so existing property-based code (body.vel.x = 5, body.isStatic = true) keeps working unchanged. Third-party adapters return their engine's native body type. For adapter-agnostic code, use the portable methods on the adapter itself (setVelocity, applyForce, etc.) instead of mutating the handle directly.

    interface PhysicsAdapter {
        capabilities: AdapterCapabilities;
        gravity: Vector2d | Vector3d;
        name?: string;
        physicLabel?: string;
        url?: string;
        version?: string;
        addBody(renderable: Renderable, def: BodyDefinition): PhysicsBody;
        addJoint?(def: JointDefinition): unknown;
        applyForce(
            renderable: Renderable,
            force: Vector2d | Vector3d,
            point?: Vector2d | Vector3d,
        ): void;
        applyImpulse(
            renderable: Renderable,
            impulse: Vector2d | Vector3d,
            point?: Vector2d | Vector3d,
        ): void;
        applyTorque?(renderable: Renderable, torque: number): void;
        destroy?(): void;
        getAngle?(renderable: Renderable): number;
        getAngularVelocity?(renderable: Renderable): number;
        getAngularVelocity3d?(renderable: Renderable, out?: Vector3d): Vector3d;
        getBodyAABB(renderable: Renderable, out: Bounds): Bounds | undefined;
        getBodyShapes(renderable: Renderable): readonly BodyShape[];
        getMaxVelocity?(renderable: Renderable): { x: number; y: number };
        getRotation?(renderable: Renderable, out?: Quaternion): Quaternion;
        getVelocity(renderable: Renderable, out?: Vector2d): Vector2d;
        getVelocity3d?(renderable: Renderable, out?: Vector3d): Vector3d;
        init?(world: World): void;
        isGrounded?(renderable: Renderable): boolean;
        isSleeping?(renderable: Renderable): boolean;
        queryAABB(rect: Rect): Renderable[];
        querySphere?(center: Vector3d, radius: number): Renderable[];
        querySphere?(sphere: Sphere): Renderable[];
        raycast?(from: Vector2d, to: Vector2d): RaycastHit | null;
        raycast3d?(from: Vector3d, to: Vector3d): RaycastHit3d | null;
        removeBody(renderable: Renderable): void;
        removeJoint?(joint: unknown): void;
        setAngle?(renderable: Renderable, angle: number): void;
        setAngularVelocity?(renderable: Renderable, omega: number | Vector3d): void;
        setCollisionMask(renderable: Renderable, mask: number): void;
        setCollisionType(renderable: Renderable, type: number): void;
        setFrictionAir(
            renderable: Renderable,
            friction: number | { x: number; y: number },
        ): void;
        setGravityScale(renderable: Renderable, scale: number): void;
        setMaxVelocity(
            renderable: Renderable,
            limit: { x: number; y: number; z?: number },
        ): void;
        setPosition(renderable: Renderable, p: Vector2d | Vector3d): void;
        setRotation?(renderable: Renderable, q: Quaternion): void;
        setSensor?(renderable: Renderable, isSensor: boolean): void;
        setStatic(renderable: Renderable, isStatic: boolean): void;
        setVelocity(renderable: Renderable, v: Vector2d | Vector3d): void;
        step(dt: number): void;
        syncFromPhysics(): void;
        syncToPhysics?(renderable: Renderable): void;
        updateShape?(renderable: Renderable, shapes: BodyShape[]): void;
    }

    Implemented by

    Index
    capabilities: AdapterCapabilities

    advertised capabilities; user code may branch on these

    gravity: Vector2d | Vector3d

    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.

    name?: string

    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?: string

    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.

    url?: string

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

    version?: string

    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 PhysicsBody

    • Make a joint between the bodies of def.a and def.b and return the engine's own joint, or null when this adapter has no joints (capabilities.constraints is false), which makes World#addJoint throw. Called by World#addJoint, which game code uses instead: the world keeps the joint, rebuilds it on World#setAdapter and removes it with its bodies. The adapter writes the defaults it resolves (anchorA, a rope's maxLength) onto def, the world's own copy, so that a rebuild makes the same joint.

      Parameters

      Returns unknown

    • Return the body's axis-aligned bounding box in renderable-local coordinates (relative to renderable.pos). Writes into the supplied out Bounds so callers can poll allocation-free each frame. Returns undefined if the renderable has no registered body.

      Used by ecosystem tooling — most notably @melonjs/debug-plugin — to visualize the body's effective collision extent. The adapter owns coordinate-system conversion: builtin Body already stores bounds in local space, matter stores them in world space and the adapter subtracts renderable.pos before writing.

      Required by the adapter contract: any adapter that registers bodies MUST implement this. The output is the canonical, local- space representation tools rely on regardless of which engine the adapter wraps.

      Parameters

      Returns Bounds | undefined

    • Return a snapshot of the body's collision shapes in renderable-local coordinates. The returned array is intended for read-only inspection (debug drawing, hit-region queries) — adapters may return a live reference for performance, so callers MUST NOT mutate it. Returns an empty array if no body.

      Pairs with getBodyAABB as the adapter-side debug surface; lets each adapter own its coordinate convention without polluting the underlying physics-engine body objects. Required by the adapter contract.

      Parameters

      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 the engine has put this 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. A static or kinematic body, an unregistered renderable, and every body of an adapter without AdapterCapabilities.sleepingBodies (the builtin one) are never asleep. Read it to tell when a throw, a stack or a level has settled.

      Parameters

      Returns boolean

      // the level is over once every crate has come to rest
      const settled = crates.every((c) => world.adapter.isSleeping?.(c) ?? false);
    • Optional 3D sphere region query — returns renderables whose getAbsolutePosition() lies within radius of center. The narrow phase is a point-in-sphere test against each candidate's centre; callers wanting bounding-sphere overlap should intersect with the candidate's bounds afterwards.

      Two call shapes:

      • querySphere(center: Vector3d, radius: number) — loose form
      • querySphere(sphere: Sphere) — packaged form, the idiomatic surface once a query shape needs to be passed around or cached

      Active only under a 3D broadphase (Octree, set when world.sortOn === "depth"). Adapters that don't expose a 3D spatial index omit the method.

      Parameters

      Returns Renderable[]

      // Loose form — quick one-off query:
      const nearby = world.adapter.querySphere?.(enemy.pos, HIT_RADIUS);
      // Idiomatic form — give an entity its own bounding sphere and
      // reuse it each frame:
      import { Sphere } from "melonjs";

      class Enemy extends Renderable {
      collider = new Sphere(0, 0, 0, 30);

      update(dt) {
      // keep the sphere glued to this renderable's pose
      this.collider.pos.set(this.pos.x, this.pos.y, this.pos.z);
      // query — returns every renderable whose centre is within
      // this enemy's collider
      const nearby = world.adapter.querySphere?.(this.collider) ?? [];
      for (const r of nearby) {
      // narrow-phase / kind filter / etc.
      }
      return super.update(dt);
      }
      }
    • Parameters

      Returns Renderable[]

    • Unregister a body. Called automatically when Container.removeChild detaches the renderable; direct calls are the inverse of a direct addBody (rare — use removeChild for the normal lifecycle).

      Parameters

      Returns void

    • Turn the body to an orientation in 3D. The built-in adapter, whose bodies turn about Z only, applies the part of it about Z.

      Parameters

      Returns void

      // stand a crate on its side
      world.adapter.setRotation?.(crate, new Quaternion().rotate(Math.PI / 2, new Vector3d(0, 0, 1)));
    • 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