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

54 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-03-24 01:16:24 -05:00
import {compose, virtualize} from '@avocado/core';
import {Vector} from '@avocado/math';
2019-03-24 01:16:24 -05:00
const decorate = compose(
virtualize([
'addBody',
'createBody',
]),
);
export class AbstractWorld extends decorate(class {}) {
2019-03-24 01:16:24 -05:00
constructor() {
super();
2019-03-24 01:16:24 -05:00
this.entities = new Map();
2019-04-16 14:04:11 -05:00
this.entitiesList = [];
2019-03-24 01:16:24 -05:00
}
associateBodyWithEntity(body, entity) {
this.entities.set(body, entity);
2019-04-16 14:04:11 -05:00
this.entitiesList.push(entity);
2019-03-24 01:16:24 -05:00
body.position = entity.position;
}
removeBody(body) {
2019-04-16 14:04:11 -05:00
if (this.entities.has(body)) {
const entity = this.entities.get(body);
this.entities.delete(body);
const index = this.entitiesList.indexOf(entity);
if (-1 !== index) {
this.entitiesList.splice(index, 1);
}
}
2019-03-24 01:16:24 -05:00
}
tick(elapsed) {
// Propagate position updates.
2019-04-16 14:04:11 -05:00
for (let i = 0; i < this.entitiesList.length; ++i) {
const entity = this.entitiesList[i];
const entityPosition = entity.position;
const bodyPosition = entity.body.position;
2019-04-16 14:04:11 -05:00
// Hot.
if (
entityPosition[0] === bodyPosition[0]
&& entityPosition[1] === bodyPosition[1]
) {
continue;
}
2019-03-24 01:16:24 -05:00
entity.position = entity.body.position;
}
}
}