How to Use Matter.Body.set in Matter.js

In Matter.js, updating several physical attributes of a rigid body can become verbose if changed individually. This article explains how to use the Matter.Body.set function to apply multiple properties to a physics body at once. You will learn the required syntax, how the method safely updates internal states, and see a practical code example demonstrating simultaneous property assignment.


The Matter.Body.set Syntax

The Matter.Body.set method accepts either a key-value pair for a single property or a configuration object containing multiple properties. To update multiple properties simultaneously, pass the target body as the first argument and an object containing the new attributes as the second argument:

Matter.Body.set(body, settings);

Why Use Matter.Body.set Instead of Direct Mutation?

While it is technically possible to mutate properties directly (e.g., body.isStatic = true), doing so can break the physics simulation. Properties like mass, density, inertia, and position require recalculations of bounds, inverse masses, and collision vectors.

When you pass an object to Matter.Body.set, the function iterates over each key and delegates the assignment to specific helper functions (such as Body.setStatic, Body.setMass, or Body.setAngle) where necessary. This ensures that all internal calculations and dependent properties update synchronously.

Example: Applying Multiple Properties

Below is a practical implementation demonstrating how to apply visual and physical changes—such as restitution, friction, static state, and render options—in a single call:

// 1. Create a dynamic body
const box = Matter.Bodies.rectangle(400, 200, 80, 80, {
    mass: 5,
    restitution: 0.2
});

// 2. Add it to your Matter.js world
Matter.Composite.add(engine.world, box);

// 3. Apply multiple properties at once
Matter.Body.set(box, {
    isStatic: true,
    restitution: 0.9,
    friction: 0.05,
    frictionAir: 0.01,
    angle: Math.PI / 4,
    render: {
        fillStyle: '#ff4757',
        strokeStyle: '#2f3542',
        lineWidth: 3
    }
});

Supported Properties

You can include any standard body property inside the settings object, including:

Using Matter.Body.set keeps your code clean, concise, and ensures that the physics engine stays in a valid internal state when modifying active simulation objects.