An attractors plugin for matter.js
This plugin makes it easy to apply continual forces on bodies. It's possible to simulate effects such as wind, gravity and magnetism.
See the demo.
Get the matter-attractors.js file directly or get it via npm:
npm install matter-attractors
Matter.use('matter-attractors');
// or
Matter.use(MatterAttractors);
See Using Plugins for more information.
Attractors are just functions that are pushed to body.plugin.attractors
.
An attractor function accepts two bodies bodyA
and bodyB
, where bodyA
is
always the attracting body and bodyB
is the body being attracted.
The attractor will be called against every other body in the engine in the place of bodyB
,
on every engine update. If a force is returned, it will be applied to bodyB
only.
An example of a body that attracts other bodies to it:
var body = Matter.Bodies.circle(0, 0, 10, {
plugin: {
attractors: [
function(bodyA, bodyB) {
return {
x: (bodyA.position.x - bodyB.position.x) * 1e-6,
y: (bodyA.position.y - bodyB.position.y) * 1e-6,
};
}
]
}
);
It's possible here to use collision filters too if needed, by using Detector.canCollide
and returning null
to skip the pair.
In advance usage, e.g. where forces apply to both bodies, instead of returning the force it can instead
be applied manually to both bodies inside the function using Body.applyForce
.
var body = Matter.Bodies.circle(0, 0, 10, {
plugin: {
attractors: [
function(bodyA, bodyB) {
var force = {
x: (bodyA.position.x - bodyB.position.x) * 1e-6,
y: (bodyA.position.y - bodyB.position.y) * 1e-6,
};
// apply force to both bodies
Body.applyForce(bodyA, bodyA.position, Matter.Vector.neg(force));
Body.applyForce(bodyB, bodyB.position, force);
}
]
}
);
There are some attractors you can push to body.plugin.attractors
:
MatterAttractors.Attractors.gravity
- uses Newton's gravitational laws to apply an attractive force on both bodiesSee the API docs.
Check out the examples or try them out first: