What is engine.world in Matter.js?

In Matter.js, the engine.world property serves as the top-level container and physical environment for a 2D physics simulation. It is a specialized Composite instance that holds every physical body, constraint, and nested composite that the engine simulates. Understanding engine.world is essential for creating simulations, as it dictates what objects exist in the physics loop, how global forces like gravity behave, and what data gets passed to renderers.

The Role of engine.world

When you initialize an engine using Engine.create(), Matter.js automatically creates a root Composite and assigns it to engine.world.

The primary purposes of engine.world include:

Basic Usage

To add objects to the simulation space, developers pass engine.world as the target container to the Composite.add method:

// Initialize engine
const engine = Matter.Engine.create();

// Configure global properties
engine.world.gravity.y = 1; // Standard downward gravity

// Create physical bodies
const ground = Matter.Bodies.rectangle(400, 600, 810, 60, { isStatic: true });
const box = Matter.Bodies.rectangle(400, 200, 80, 80);

// Register bodies to the world
Matter.Composite.add(engine.world, [ground, box]);

In summary, engine.world acts as the single source of truth for the spatial state of your Matter.js application, binding individual physical entities to the engine's step calculations and broadphase collision detection routines.