61 lines
1.3 KiB
JavaScript
61 lines
1.3 KiB
JavaScript
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);
|
|
}
|
|
|
|
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]),
|
|
];
|
|
}
|
|
|
|
toJSON() {
|
|
return {
|
|
...super.toJSON(),
|
|
type: 'rectangle',
|
|
position: this.position,
|
|
size: this.size,
|
|
}
|
|
}
|
|
|
|
}
|