avocado-old/packages/physics/rectangle.js

61 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-03-22 11:25:20 -05:00
import {compose} from '@avocado/core';
import {Vector} from '@avocado/math';
import {PolygonShape} from './polygon';
const decorate = compose(
Vector.Mixin('size', 'width', 'height', {
default: [0, 0],
track: true,
}),
);
export class RectangleShape extends decorate(PolygonShape) {
constructor() {
super();
this.on(['positionChanged', 'sizeChanged'], this.onVerticesChanged, this);
}
destroy() {
super.destroy();
this.off(['positionChanged', 'sizeChanged'], this.onVerticesChanged);
2019-03-22 11:25:20 -05:00
}
fromJSON(json) {
super.fromJSON(json);
const keys = [
'size',
];
for (const key of keys) {
if (json[key]) {
this[key] = json[key];
}
}
return this;
}
onVerticesChanged() {
const halfSize = Vector.scale(this.size, 0.5);
const width = this.width - 0.001;
const height = this.height - 0.001;
const position = Vector.add(this.position, Vector.scale(halfSize, -1));
this.vertices = [
position,
Vector.add(position, [width, 0]),
Vector.add(position, [width, height]),
Vector.add(position, [0, height]),
];
}
2019-03-22 11:25:20 -05:00
toJSON() {
return {
...super.toJSON(),
type: 'rectangle',
position: this.position,
size: this.size,
}
}
}