Create a Pendulum Using Matter.js Constraints

This guide demonstrates how to simulate a physical pendulum in Matter.js by connecting a dynamic body to a fixed point using the engine's built-in constraint system. You will learn how to initialize the required modules, define the pendulum bob, configure the constraint parameters, and run the physics simulation.

1. Import Matter.js Modules

To build the pendulum, extract the core modules from the Matter object. You will need Engine, Render, Runner, Bodies, Composite, and Constraint.

const { Engine, Render, Runner, Bodies, Composite, Constraint } = Matter;

const engine = Engine.create();
const world = engine.world;

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

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

2. Create the Pendulum Bob

The bob is a standard dynamic body that responds to gravity. Offset its initial horizontal position from the anchor point so gravity naturally initiates the swing.

const bob = Bodies.circle(500, 300, 30, {
  density: 0.005,
  frictionAir: 0.001,
  render: {
    fillStyle: '#e74c3c'
  }
});

3. Create the Constraint

A constraint links two bodies together, or links a single body to a fixed coordinate in the world space. To build a simple pendulum, specify a static world position using pointA and attach it to the bob via bodyB.

const pendulumArm = Constraint.create({
  pointA: { x: 400, y: 100 }, // Fixed pivot point in the world
  bodyB: bob,                  // The swinging body
  pointB: { x: 0, y: 0 },      // Connection point relative to the bob's center
  stiffness: 1,                // 1 creates a rigid rod; lower values simulate an elastic rope
  damping: 0,                  // Energy dissipation in the constraint
  length: 250,                 // Length of the arm in pixels
  render: {
    strokeStyle: '#ffffff',
    lineWidth: 3
  }
});

4. Add Elements to the World

Add both the bob and the constraint to the physics composite to activate the simulation.

Composite.add(world, [bob, pendulumArm]);

Key Properties to Customize