0
0
Fork 0
mirror of https://github.com/liabru/matter-js.git synced 2024-11-27 09:50:52 -05:00
liabru-matter-js/examples/gravityPlugin.js

49 lines
1.3 KiB
JavaScript
Raw Normal View History

(function() {
var MatterGravity = {
name: 'matter-gravity',
version: '0.1.0',
for: 'matter-js@^0.10.0',
uses: [
'matter-attractors@^0.1.0'
],
install: function(base) {
2016-11-02 20:49:22 -04:00
base.after('Body.create', function() {
MatterGravity.Body.init(this);
});
},
2016-10-15 18:23:35 -04:00
Body: {
init: function(body) {
if (body.gravity) {
body.attractors.push(MatterGravity.Body.applyGravity);
}
},
applyGravity: function(bodyA, bodyB) {
2016-11-02 20:49:22 -04:00
var Vector = Matter.Vector,
Body = Matter.Body,
bToA = Vector.sub(bodyB.position, bodyA.position),
2016-10-15 18:23:35 -04:00
distanceSq = Vector.magnitudeSquared(bToA) || 0.0001,
normal = Vector.normalise(bToA),
magnitude = -bodyA.gravity * (bodyA.mass * bodyB.mass / distanceSq),
force = Vector.mult(normal, magnitude);
Body.applyForce(bodyA, bodyA.position, Vector.neg(force));
Body.applyForce(bodyB, bodyB.position, force);
}
}
};
Matter.Plugin.register(MatterGravity);
2016-11-03 20:04:56 -04:00
if (typeof window !== 'undefined') {
window.MatterGravity = MatterGravity;
}
})();