avocado-old/packages/entity/traits/physical.js

93 lines
1.8 KiB
JavaScript
Raw Normal View History

2019-03-22 13:16:07 -05:00
import {compose} from '@avocado/core';
2019-03-23 18:26:35 -05:00
import {ShapeView} from '@avocado/graphics';
2019-03-22 13:16:07 -05:00
import {Vector} from '@avocado/math';
import {shapeFromJSON} from '@avocado/physics';
2019-03-23 23:24:18 -05:00
import {StateProperty, Trait} from '../trait';
2019-03-22 13:16:07 -05:00
const decorate = compose(
);
export class Physical extends decorate(Trait) {
static defaultParams() {
return {
shape: undefined,
};
}
initialize() {
2019-03-23 18:26:35 -05:00
this._body = undefined;
2019-03-22 13:16:07 -05:00
this._shape = shapeFromJSON(this.params.get('shape'));
2019-03-23 18:26:35 -05:00
this._shapeView = undefined;
this._world = undefined;
}
destroy() {
if (this._world) {
this._world.removeBody(this._body);
}
}
get body() {
return this._body;
2019-03-22 13:16:07 -05:00
}
get shape() {
return this._shape;
}
2019-03-23 18:26:35 -05:00
set world(world) {
this._world = world;
if (world) {
2019-03-24 01:16:24 -05:00
const body = world.createBody(this.entity.shape);
world.associateBodyWithEntity(body, this.entity);
world.addBody(body);
this._body = body;
2019-03-23 18:26:35 -05:00
}
}
listeners() {
return {
addedToList: () => {
this.entity.world = this.entity.list.world;
},
positionChanged: () => {
if (this._body) {
this._body.position = this.entity.position;
}
},
traitAdded: (type) => {
if (!this._shapeView && this.entity.container) {
this._shapeView = new ShapeView(this.entity.shape);
this._shapeView.zIndex = 100;
this.entity.container.addChild(this._shapeView);
}
}
};
}
methods() {
return {
applyForce: (force) => {
if (this._world) {
this._body.applyForce(force);
}
},
2019-03-24 03:24:35 -05:00
applyImpulse: (impulse, elapsed) => {
2019-03-23 18:26:35 -05:00
if (this._world) {
2019-03-24 03:24:35 -05:00
this._body.applyImpulse(impulse, elapsed);
2019-03-23 18:26:35 -05:00
}
},
}
}
2019-03-22 13:16:07 -05:00
}