avocado-old/packages/physics/polygon.js

98 lines
2.3 KiB
JavaScript

import {Rectangle, Vector, Vertice} from '@avocado/math';
import {Shape} from './shape';
export class PolygonShape extends Shape {
constructor() {
super();
this._translatedVertices = [];
this._vertices = [];
this.on([
'parentOriginChanged',
'parentRotationChanged',
'parentScaleChanged',
'originChanged',
'rotationChanged',
'scaleChanged',
'verticesChanged',
], this.onRecalculateVertices, this);
}
destroy() {
super.destroy();
this.off([
'parentOriginChanged',
'parentRotationChanged',
'parentScaleChanged',
'originChanged',
'rotationChanged',
'scaleChanged',
'verticesChanged',
], this.onRecalculateVertices);
}
*[Symbol.iterator]() {
for (const vertice of this._translatedVertices) {
yield vertice;
}
}
get aabb() {
if (0 === this._vertices.length) {
return [0, 0, 0, 0];
}
const min = [Infinity, Infinity];
const max = [-Infinity, -Infinity];
for (const vertice of this._translatedVertices) {
min[0] = vertice[0] < min[0] ? vertice[0] : min[0];
min[1] = vertice[1] < min[1] ? vertice[1] : min[1];
max[0] = vertice[0] > max[0] ? vertice[0] : max[0];
max[1] = vertice[1] > max[1] ? vertice[1] : max[1];
}
return Rectangle.translated(
[min[0], min[1], max[0] - min[0], max[1] - min[1]],
this.position
);
}
fromJSON(json) {
super.fromJSON(json);
if (json.vertices) {
this.vertices = json.vertices;
}
return this;
}
onRecalculateVertices() {
const parentOrigin = this.parent ? this.parent.origin : [0, 0];
const origin = Vector.add(this.origin, parentOrigin);
const parentRotation = this.parent ? this.parent.rotation : 0;
const rotation = this.rotation + parentRotation;
const parentScale = this.parent ? this.parent.scale : 1;
const scale = this.scale * parentScale;
this._translatedVertices = this._vertices.map((vertice) => {
return Vertice.translate(vertice, origin, rotation, scale);
});
this.emit('aabbChanged');
}
get vertices() {
return this._vertices;
}
set vertices(vertices) {
this._vertices = [...vertices];
this.emit('verticesChanged');
}
toJSON() {
return {
...super.toJSON(),
type: 'polygon',
vertices: [...this._vertices]
}
}
}