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:
- The Attractor Function: Each attractor body
contains an array of functions. These functions take two arguments: the
body exerting the force (
bodyA) and the body receiving the force (bodyB). - Vector Math: The function calculates the distance
and angle between the two bodies, computes the appropriate magnitude of
force, and applies it directly to
bodyBusing Matter.js vector forces. - Custom Calculations: Developers can define standard inverse-square laws (Newtonian gravity), linear falloff, constant push/pull fields, or complex conditional forces that only activate within specific radii.
Common Use Cases
- Orbital Mechanics and Space Simulations: Creating suns, planets, and moons where smaller bodies enter stable orbits around larger bodies based on simulated gravitational pull.
- Magnetic Fields: Simulating positive and negative magnetic poles that attract opposite charges while repelling identical ones.
- Gameplay Mechanics: Power-ups such as "coin magnets" that pull collectible items toward the player character, or vortex hazards and black holes that trap objects.
- Repulsion Fields: Creating defensive shields, wind corridors, or bouncy zones that push approaching objects away smoothly without relying entirely on rigid body collisions.