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

90 lines
1.8 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
2019-04-08 13:32:40 -05:00
import {Trait} from '../trait';
2019-03-22 13:16:07 -05:00
const decorate = compose(
);
export class Physical extends decorate(Trait) {
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() {
if (this._world) {
this._world.removeBody(this._body);
}
2019-03-24 18:58:32 -05:00
if (this.bodyView) {
this.bodyView.destroy();
}
2019-03-23 18:26:35 -05:00
}
get body() {
return this._body;
2019-03-22 13:16:07 -05:00
}
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);
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
}
}
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
}
},
};
}
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
}