Skip to content

liabru/matter-attractors

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

matter-attractors

An attractors plugin for matter.js

Build Status

This plugin makes it easy to apply continual forces on bodies. It's possible to simulate effects such as wind, gravity and magnetism.

Demo

See the demo.

matter-attractors

Install

Get the matter-attractors.js file directly or get it via npm:

npm install matter-attractors

Dependencies

Usage

Matter.use('matter-attractors');
// or
Matter.use(MatterAttractors);

See Using Plugins for more information.

Custom attractors

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.

Basic usage

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.

Advance usage

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);
      }
    ]
  }
);

Built in attractors

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 bodies

Documentation

See the API docs.

Examples

Check out the examples or try them out first: