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

115 lines
2.4 KiB
JavaScript
Raw Normal View History

2019-03-22 13:16:07 -05:00
import {compose} from '@avocado/core';
2019-03-24 18:58:32 -05:00
import {Color, Container, Primitives, ShapeView} from '@avocado/graphics';
import {Rectangle, Vector} from '@avocado/math';
import {BodyView, shapeFromJSON} from '@avocado/physics';
2019-03-22 13:16:07 -05:00
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-24 18:58:32 -05:00
this.bodyView = undefined;
2019-03-22 13:16:07 -05:00
this._shape = shapeFromJSON(this.params.get('shape'));
2019-03-24 18:58:32 -05:00
this.shapeView = undefined;
2019-03-23 18:26:35 -05:00
this._world = undefined;
}
destroy() {
if (this._world) {
this._world.removeBody(this._body);
}
2019-03-24 18:58:32 -05:00
if (this.bodyView) {
this.bodyView.destroy();
}
if (this.shapeView) {
this.shapeView.destroy();
}
2019-03-23 18:26:35 -05:00
}
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) {
2019-03-27 16:11:37 -05:00
if (this._world) {
this._world.removeBody(this._body);
}
if (this.bodyView) {
this.bodyView.destroy();
}
2019-03-23 18:26:35 -05:00
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-24 18:58:32 -05:00
if (this.entity.container) {
this.bodyView = new BodyView(body);
this.bodyView.position = Vector.scale(this.entity.position, -1);
this.bodyView.zIndex = 101;
this.entity.container.addChild(this.bodyView);
}
2019-03-23 18:26:35 -05:00
}
}
listeners() {
return {
2019-03-27 01:49:48 -05:00
addedToRoom: () => {
this.entity.world = this.entity.room.world;
2019-03-23 18:26:35 -05:00
},
positionChanged: () => {
if (this._body) {
2019-03-24 18:58:32 -05:00
const position = this.entity.position;
this._body.position = position;
2019-03-23 18:26:35 -05:00
}
},
traitAdded: (type) => {
2019-03-24 18:58:32 -05:00
if (this.entity.container) {
if (!this.shapeView) {
this.shapeView = new ShapeView(this.entity.shape);
this.shapeView.zIndex = 100;
this.entity.container.addChild(this.shapeView);
}
2019-03-23 18:26:35 -05:00
}
}
};
}
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
}