avocado-old/packages/physics/matter/world.js

67 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-03-27 18:38:12 -05:00
import {Engine, Events, World as MatterWorld} from 'matter-js';
2019-03-24 03:24:35 -05:00
import {Body} from './body';
import {AbstractWorld} from '../abstract/world';
export class World extends AbstractWorld {
constructor() {
super();
const world = MatterWorld.create({
gravity: {
x: 0,
y: 0,
scale: 0,
},
});
this.engine = Engine.create({
world,
});
2019-03-27 18:38:12 -05:00
this.handleCollisions('collisionStart');
this.handleCollisions('collisionEnd');
this.elapsedRemainder = 0;
2019-03-24 03:24:35 -05:00
}
addBody(body) {
MatterWorld.add(this.engine.world, body.matterBody);
}
createBody(shape) {
return new Body(shape);
}
2019-03-27 18:38:12 -05:00
handleCollisions(eventName) {
Events.on(this.engine, eventName, (event) => {
event.pairs.forEach((pair) => {
const {bodyA, bodyB} = pair;
const entityA = this.entities.get(Body.lookupBody(bodyA));
const entityB = this.entities.get(Body.lookupBody(bodyB));
if (entityA && entityB) {
entityA.emit(eventName, entityB);
entityB.emit(eventName, entityA);
}
});
});
}
2019-03-24 03:24:35 -05:00
removeBody(body) {
super.removeBody(body);
MatterWorld.remove(this.engine.world, body.matterBody);
2019-03-24 03:24:35 -05:00
}
tick(elapsed) {
// Update simulation.
elapsed += this.elapsedRemainder;
const stepTime = this.stepTime;
2019-05-04 13:15:34 -05:00
const stepTimeInMs = stepTime * 1000;
while (elapsed >= stepTime) {
Engine.update(this.engine, stepTimeInMs);
elapsed -= stepTime;
}
this.elapsedRemainder = elapsed;
2019-03-24 03:24:35 -05:00
// Propagate.
super.tick(elapsed);
}
}