avocado-old/packages/physics/shape-view.js
2019-04-21 02:54:07 -05:00

79 lines
1.9 KiB
JavaScript

import {Color, Container, Primitives, Renderable} from '@avocado/graphics';
import {ShapeList} from './list';
import {CircleShape} from './circle';
import {PolygonShape} from './polygon';
export class ShapeView extends Renderable {
constructor(shape) {
super();
this.container = new Container();
this.shape = shape;
if (shape instanceof PolygonShape) {
this.redrawPolygonLines();
shape.on('aabbChanged', () => {
this.redrawPolygonLines();
});
}
if (shape instanceof CircleShape) {
this.redrawCircle();
shape.on('aabbChanged', () => {
this.redrawCircle();
});
}
if (shape instanceof ShapeList) {
for (const child of shape) {
const childShapeView = new ShapeView(child);
this.container.addChild(childShapeView);
}
}
this.container.position = shape.position;
shape.on('positionChanged', () => {
this.container.position = shape.position;
})
}
get internal() {
return this.container.internal;
}
redrawCircle() {
const primitives = new Primitives();
primitives.drawCircle(
this.shape.position,
this.shape.radius,
Primitives.lineStyle(new Color(255, 0, 255), 1),
);
this.container.removeAllChildren();
this.container.addChild(primitives);
}
redrawPolygonLines() {
const primitives = new Primitives();
let firstVertice;
let lastVertice;
for (const vertice of this.shape) {
if (!firstVertice) {
firstVertice = vertice;
}
if (lastVertice) {
primitives.drawLine(
lastVertice,
vertice,
Primitives.lineStyle(new Color(255, 0, 255), 1),
);
}
lastVertice = vertice;
}
primitives.drawLine(
lastVertice,
firstVertice,
Primitives.lineStyle(new Color(255, 0, 255), 1),
);
this.container.removeAllChildren();
this.container.addChild(primitives);
}
}