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

121 lines
2.4 KiB
JavaScript
Raw Normal View History

2019-03-22 13:16:07 -05:00
import {compose} from '@avocado/core';
2019-04-08 13:32:40 -05:00
import {Vector} from '@avocado/math';
import {BodyView} from '@avocado/physics';
2019-03-22 13:16:07 -05:00
import {StateProperty, Trait} from '../trait';
2019-03-22 13:16:07 -05:00
const decorate = compose(
StateProperty('addedToPhysics', {
track: true,
}),
2019-03-22 13:16:07 -05:00
);
export class Physical extends decorate(Trait) {
static defaultState() {
return {
addedToPhysics: true,
};
}
2019-03-22 13:16:07 -05:00
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-23 18:26:35 -05:00
this._world = undefined;
}
destroy() {
2019-04-14 16:07:31 -05:00
this.world = undefined;
2019-03-22 13:16:07 -05:00
}
addToWorld() {
const world = this._world;
2019-03-23 18:26:35 -05:00
if (world) {
2019-03-24 01:16:24 -05:00
const body = world.createBody(this.entity.shape);
world.associateBodyWithEntity(body, this.entity);
2019-04-08 15:20:28 -05:00
body.setCollisionForEntity(this.entity);
2019-03-24 01:16:24 -05:00
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
}
}
get body() {
return this._body;
}
removeFromWorld() {
if (this._world && this._body) {
this._world.removeBody(this._body);
}
this._body = undefined;
if (this.bodyView) {
2019-04-14 18:42:13 -05:00
if (this.entity.is('visible')) {
2019-04-14 16:09:41 -05:00
this.entity.container.removeChild(this.bodyView);
}
this.bodyView.destroy();
}
this.bodyView = undefined;
}
set world(world) {
this.removeFromWorld();
this._world = world;
this.addToWorld();
}
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
},
addedToPhysicsChanged: () => {
if (this.entity.addedToPhysics) {
if (!this._body) {
this.addToWorld();
}
}
else {
if (this._body) {
this.removeFromWorld();
}
}
},
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
}
},
};
}
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
}