How to Scale a Composite in Matter.js

Scaling an entire composite in Matter.js allows developers to uniformly or non-uniformly resize a collection of bodies, constraints, and nested composites relative to a designated focal point. This guide covers how to use the built-in Matter.Composite.scale function, explains its required parameters, demonstrates practical code implementation, and highlights key considerations when resizing complex physics assemblies.

Understanding Composite.scale

Matter.js provides a dedicated method within the Composite module to handle scaling of compound objects. Rather than manually resizing each individual body and adjusting constraints, Composite.scale resizes all contained physical elements simultaneously.

The method signature is:

Matter.Composite.scale(composite, scaleX, scaleY, point, [recursive=true])

Parameters


Implementation Example

To scale a composite, group your bodies and constraints into a Composite instance, select an anchor point, and pass them into Composite.scale.

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

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

// 2. Create individual bodies
const boxA = Bodies.rectangle(200, 200, 80, 80);
const boxB = Bodies.rectangle(300, 200, 80, 80);

// 3. Connect them with a constraint
const link = Constraint.create({
    bodyA: boxA,
    bodyB: boxB,
    stiffness: 0.9
});

// 4. Group them into a single Composite
const carAssembly = Composite.create();
Composite.add(carAssembly, [boxA, boxB, link]);
Composite.add(world, carAssembly);

// 5. Define an origin point for scaling (e.g., center of boxA)
const scaleOrigin = { x: 200, y: 200 };

// 6. Scale the entire composite to 1.5x its original size
Composite.scale(carAssembly, 1.5, 1.5, scaleOrigin);

Key Considerations