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:
- Object Management: Any rigid body (such as
rectangles, circles, or custom polygons) or constraint (such as springs
or distance joints) must be added to
engine.worldto participate in collision detection and physical updates. If an object is not added to this world instance—or to a composite nested within it—the engine will ignore it. - Global Physics Configuration: Properties affecting
the entire environment, such as gravity, are configured directly through
engine.world. By adjustingengine.world.gravity.x,engine.world.gravity.y, orengine.world.gravity.scale, you define the directional acceleration applied to all dynamic bodies in the scene. - Hierarchical Organization: Because
engine.worldis aComposite, it can hold other composites. This allows developers to group related bodies and constraints into self-contained assemblies (like a vehicle or a ragdoll) and add the entire group toengine.worldin a single operation. - Renderer Integration: Visual modules, such as
Matter.Render, accept an engine reference and draw the contents of itsworld. Adding or removing an entity fromengine.worldautomatically updates both its physical behavior and its visual representation on the canvas.
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.