feat: BodyView

This commit is contained in:
cha0s 2019-03-24 18:58:32 -05:00
parent 12f87bd29d
commit b9a963d2f1
3 changed files with 61 additions and 9 deletions

View File

@ -1,7 +1,7 @@
import {compose} from '@avocado/core';
import {ShapeView} from '@avocado/graphics';
import {Vector} from '@avocado/math';
import {shapeFromJSON} from '@avocado/physics';
import {Color, Container, Primitives, ShapeView} from '@avocado/graphics';
import {Rectangle, Vector} from '@avocado/math';
import {BodyView, shapeFromJSON} from '@avocado/physics';
import {StateProperty, Trait} from '../trait';
@ -18,8 +18,9 @@ export class Physical extends decorate(Trait) {
initialize() {
this._body = undefined;
this.bodyView = undefined;
this._shape = shapeFromJSON(this.params.get('shape'));
this._shapeView = undefined;
this.shapeView = undefined;
this._world = undefined;
}
@ -27,6 +28,12 @@ export class Physical extends decorate(Trait) {
if (this._world) {
this._world.removeBody(this._body);
}
if (this.bodyView) {
this.bodyView.destroy();
}
if (this.shapeView) {
this.shapeView.destroy();
}
}
get body() {
@ -44,6 +51,12 @@ export class Physical extends decorate(Trait) {
world.associateBodyWithEntity(body, this.entity);
world.addBody(body);
this._body = body;
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);
}
}
}
@ -56,15 +69,18 @@ export class Physical extends decorate(Trait) {
positionChanged: () => {
if (this._body) {
this._body.position = this.entity.position;
const position = this.entity.position;
this._body.position = 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);
if (this.entity.container) {
if (!this.shapeView) {
this.shapeView = new ShapeView(this.entity.shape);
this.shapeView.zIndex = 100;
this.entity.container.addChild(this.shapeView);
}
}
}

View File

@ -0,0 +1,34 @@
import {Color, Primitives, Renderable} from '@avocado/graphics';
import {Rectangle, Vector} from '@avocado/math';
export class BodyView extends Renderable {
constructor(body) {
super();
this.body = body;
this.primitives = new Primitives();
this.redrawAabb();
}
get internal() {
return this.primitives.internal;
}
redrawAabb() {
const aabb = this.body.aabb;
this.primitives.clear();
const xMiddle = aabb[0] + (aabb[2] / 2);
this.primitives.drawLine(
[xMiddle, aabb[1]],
[xMiddle, aabb[1] + (aabb[3] - 0.0001)],
Primitives.lineStyle(new Color(255, 255, 0), 4)
);
const yMiddle = aabb[1] + (aabb[3] / 2);
this.primitives.drawLine(
[aabb[0], yMiddle],
[aabb[0] + (aabb[2] -0.0001), yMiddle],
Primitives.lineStyle(new Color(255, 255, 0), 4)
);
}
}

View File

@ -1,3 +1,5 @@
export {BodyView} from './body-view';
import {PolygonShape} from './polygon';
export {PolygonShape};