What Is the Matter-Attractors Plugin in Matter.js?

The matter-attractors plugin is an extension for the Matter.js 2D physics engine that enables bodies to exert continuous forces on other bodies within a simulation. While native Matter.js handles uniform directional gravity and collision physics, it lacks built-in support for dynamic, body-to-body attraction or repulsion. This guide explains what the matter-attractors plugin does, how it functions under the hood, and the most common use cases for integrating it into web-based physics simulations.

The Purpose of matter-attractors

By default, Matter.js allows you to configure a world-level gravity vector, which applies a constant downward or directional force to all dynamic objects. However, real-world interactions often require localized, non-uniform forces, such as gravity between celestial objects or magnetic polarity.

The matter-attractors plugin bridges this gap by letting individual physics bodies act as force generators. Any body configured as an attractor can continuously pull or push other objects in the world based on distance, mass, or custom mathematical formulas.

How the Plugin Works

Once installed and registered with the Matter.js engine, the plugin hooks into the engine's update loop (beforeUpdate). It reads an attractors array defined on individual bodies and executes the assigned force calculations on every frame.

Key mechanical components include:

Common Use Cases