Create Point-to-Point Constraints in Matter.js

Constraints in Matter.js allow you to simulate physical connections between objects, such as rigid rods, elastic springs, or pinned joints. This guide covers how to set up a basic point-to-point constraint between two rigid bodies using the Matter.Constraint module, detailing the required parameters, coordinate offsets, and how to add the resulting connection into your physics world.

Understanding the Constraint Module

To create a constraint, use the Constraint.create() method provided by Matter.js. A basic point-to-point constraint links a point on one body (bodyA) to a point on another body (bodyB). If you omit the bodies and only specify coordinates, you can also link directly to fixed positions in the simulation space.

Basic Implementation

Below is a complete example of creating two rectangular bodies and connecting them with a point-to-point constraint:

// Alias Matter.js modules
const { Engine, Render, Runner, Bodies, Composite, Constraint } = Matter;

// Initialize engine and world
const engine = Engine.create();
const world = engine.world;

// Create a renderer
const render = Render.create({
    element: document.body,
    engine: engine,
    options: {
        width: 800,
        height: 600,
        wireframes: false
    }
});

Render.run(render);
Runner.run(Runner.create(), engine);

// 1. Create two bodies
const bodyA = Bodies.rectangle(300, 200, 80, 40, { isStatic: true });
const bodyB = Bodies.rectangle(400, 300, 80, 40);

// 2. Create the point-to-point constraint
const pointToPointConstraint = Constraint.create({
    bodyA: bodyA,
    pointA: { x: 0, y: 0 }, // Center of bodyA
    bodyB: bodyB,
    pointB: { x: -30, y: -10 }, // Offset from center of bodyB
    stiffness: 0.9,
    damping: 0.1,
    length: 150
});

// 3. Add bodies and constraint to the world
Composite.add(world, [bodyA, bodyB, pointToPointConstraint]);

Key Configuration Properties

Pinning a Body to a Fixed World Position

To anchor a dynamic body to a specific location in space rather than to another body, omit bodyB and specify pointB as absolute world coordinates:

const pinnedConstraint = Constraint.create({
    bodyA: dynamicBody,
    pointA: { x: 0, y: 0 },
    pointB: { x: 400, y: 100 }, // Fixed world position
    stiffness: 1,
    length: 0
});

Composite.add(world, pinnedConstraint);

Setting length: 0 and stiffness: 1 effectively creates a fixed pivot or hinge joint around the specified world coordinate.