0
0
Fork 0
mirror of https://github.com/liabru/matter-js.git synced 2024-11-23 09:26:51 -05:00
liabru-matter-js/examples/attractorsPlugin.js

73 lines
2.1 KiB
JavaScript
Raw Normal View History

(function() {
var Body = Matter.Body,
Common = Matter.Common,
Composite = Matter.Composite;
var MatterAttractors = {
name: 'matter-attractors',
version: '0.1.0',
for: 'matter-js@^0.10.0',
install: function(base) {
base.Body.create = Common.chain(
Matter.Body.create,
2016-10-15 18:23:35 -04:00
function() {
MatterAttractors.Body.init(this);
}
);
base.Engine.update = Common.chain(
Matter.Engine.update,
2016-10-15 18:23:35 -04:00
function() {
MatterAttractors.Engine.update(this);
}
);
},
2016-10-15 18:23:35 -04:00
Body: {
init: function(body) {
body.attractors = body.attractors || [];
}
},
2016-10-15 18:23:35 -04:00
Engine: {
update: function(engine) {
var world = engine.world,
bodies = Composite.allBodies(world);
for (var i = 0; i < bodies.length; i += 1) {
var bodyA = bodies[i],
attractors = bodyA.attractors;
if (attractors && attractors.length > 0) {
for (var j = i + 1; j < bodies.length; j += 1) {
var bodyB = bodies[j];
for (var k = 0; k < attractors.length; k += 1) {
var attractor = attractors[k],
forceVector = attractor;
if (Common.isFunction(attractor)) {
forceVector = attractor(bodyA, bodyB);
}
if (forceVector) {
Body.applyForce(bodyB, bodyB.position, forceVector);
}
}
}
}
}
}
}
};
Matter.Plugin.register(MatterAttractors);
window.MatterAttractors = MatterAttractors;
})();