Merging Matter.js Configs with Matter.Common.extend

Matter.Common.extend simplifies entity configuration in Matter.js by providing a built-in utility to merge multiple configuration objects into a single target. When creating complex physics simulations, entities such as bodies, composites, and constraints often share base physical traits while requiring specific property overrides. By using Matter.Common.extend, developers can combine shared presets, default engine settings, and custom parameters without relying on third-party libraries or writing repetitive object-merging logic.

In Matter.js, physics entities require detailed configuration options, including mass, restitution, friction, collision filters, and nested rendering settings. Manually assigning these properties for dozens of distinct bodies creates boilerplate code and introduces bugs. While modern JavaScript provides object spread syntax (...) and Object.assign(), these native methods perform shallow copies. If an entity configuration contains nested objects—such as collisionFilter or render—a standard shallow merge replaces the entire nested object rather than merging individual sub-properties.

Matter.Common.extend resolves this by merging properties from source objects into a target object. It can recursively combine nested objects when deep merging is specified, ensuring that default nested properties (like render.lineWidth or collisionFilter.group) are preserved when overriding a specific sub-property (like render.fillStyle).

Creating Reusable Entity Archetypes

A primary benefit of Matter.Common.extend is the ability to define reusable entity templates. Instead of repeatedly declaring common physics attributes, developers can define archetypes and combine them on demand:

const defaultPhysics = {
    friction: 0.1,
    restitution: 0.8,
    density: 0.001
};

const customRender = {
    render: {
        fillStyle: '#ff5722',
        visible: true
    }
};

// Merge default physics, custom render settings, and unique instance options
const ballOptions = Matter.Common.extend({}, defaultPhysics, customRender, {
    label: 'BouncyBall',
    restitution: 0.95 // Overrides default restitution
});

const ball = Matter.Bodies.circle(100, 100, 20, ballOptions);

Eliminating External Dependencies

Physics simulations often demand lean builds. Developers frequently import utility libraries like Lodash simply to handle deep cloning and object extension. Because Matter.Common.extend is embedded within the core engine, projects can maintain modular architecture, clean configuration pipelines, and zero-dependency builds while keeping codebases lightweight and consistent.