avocado-old/packages/physics/shape-view.js

96 lines
2.4 KiB
JavaScript
Raw Normal View History

2019-03-28 02:39:04 -05:00
import {Color, Container, Primitives, Renderable} from '@avocado/graphics';
2019-03-22 13:15:57 -05:00
2019-03-28 02:39:04 -05:00
import {ShapeList} from './list';
2019-04-12 23:51:40 -05:00
import {CircleShape} from './circle';
2019-03-28 02:39:04 -05:00
import {PolygonShape} from './polygon';
2019-03-22 13:15:57 -05:00
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.onPolygonShapeAabbChanged, this);
2019-03-22 13:15:57 -05:00
}
2019-04-12 23:51:40 -05:00
if (shape instanceof CircleShape) {
this.redrawCircle();
shape.on('aabbChanged', this.onCircleShapeAabbChanged, this);
2019-04-12 23:51:40 -05:00
}
2019-03-22 13:15:57 -05:00
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.onShapePositionChanged, this);
}
destroy() {
super.destroy();
if (shape instanceof PolygonShape) {
this.shape.off('aabbChanged', this.onPolygonShapeAabbChanged);
}
if (shape instanceof CircleShape) {
this.shape.off('aabbChanged', this.onCircleShapeAabbChanged);
}
this.shape.off('aabbChanged', this.onShapePositionChanged);
2019-03-22 13:15:57 -05:00
}
get internal() {
return this.container.internal;
}
onPolygonShapeAabbChanged() {
this.redrawPolygonLines();
}
onCircleShapeAabbChanged() {
this.redrawCircle();
}
onShapePositionChanged() {
this.container.position = shape.position;
}
2019-04-12 23:51:40 -05:00
redrawCircle() {
const primitives = new Primitives();
primitives.drawCircle(
this.shape.position,
this.shape.radius,
2019-04-21 02:54:07 -05:00
Primitives.lineStyle(new Color(255, 0, 255), 1),
2019-04-12 23:51:40 -05:00
);
this.container.removeAllChildren();
this.container.addChild(primitives);
}
2019-03-22 13:15:57 -05:00
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,
2019-04-21 02:54:07 -05:00
Primitives.lineStyle(new Color(255, 0, 255), 1),
2019-03-22 13:15:57 -05:00
);
}
lastVertice = vertice;
}
primitives.drawLine(
lastVertice,
firstVertice,
2019-04-21 02:54:07 -05:00
Primitives.lineStyle(new Color(255, 0, 255), 1),
2019-03-22 13:15:57 -05:00
);
this.container.removeAllChildren();
this.container.addChild(primitives);
}
}