mwg API
    Preparing search index...

    Class PhysicsWorld

    Rigid bodies and constraints in plain TypeScript, stepped on a fixed clock.

    The framework side of game physics in a mwg game: it owns the solver, steps it with a FixedStepper so the simulation is the same at any display refresh rate, and reports contacts through a Signal, while leaving the bodies themselves as plain objects a game reads position and angle from to place its sprites. It is renderer-free, so a game's headless tests can run the same world. No third-party engine: semi-implicit Euler, impulse contacts with restitution and Coulomb friction, and projected distance joints.

    Bodies never spin: angle stays where a game puts it (a display offset), collisions use the unrotated shape, and joints rotate their attachment points by it. Circles and axis-aligned boxes collide with each other in every pairing; that is the whole shape catalogue, by design rather than by omission - a game needing polygons brings its own.

    Constraints are springs and rods. Give one a maxStretch and it breaks when pulled that far past its rest length (onBreak); a game with a different stress rule reads stretchOf itself and calls remove.

    import { PhysicsWorld } from '@datamoc/mwg/physics';

    const world = new PhysicsWorld();
    world.addBox(0, 300, 800, 20, { isStatic: true });
    const crate = world.addBox(100, 0, 40, 40, { restitution: 0.3 });
    world.update(1 / 30); // two fixed steps
    console.log(crate.position.y > 0); // true: it has started to fall
    Index
    onBreak: Signal<{ constraint: PhysicsConstraint; stretch: number }> = ...

    fires when a breakable constraint passes its maxStretch; it is already removed from the world

    onContact: Signal<{ a: PhysicsBody; b: PhysicsBody }> = ...

    fires once per new contact between two bodies, with the bodies of the pair

    • get alpha(): number

      how far into the next fixed step the clock is, 0 to 1, for interpolated drawing

      Returns number

    • How far a constraint is stretched past its rest length, as a fraction of it (0.1 is 10% longer); for a zero-length joint, the distance between its ends. Negative when compressed.

      Parameters

      Returns number

    • Advances the simulation by dt seconds of real time, running as many fixed steps as that covers; call it from Scene.update(dt).

      Parameters

      • dt: number

      Returns number

      how many fixed steps ran