forum-logic/src/classes/supporting/geometry/rectangle.js

47 lines
1.5 KiB
JavaScript

import { Polygon } from './polygon.js';
import { Vector } from './vector.js';
export class Rectangle extends Polygon {
constructor(position, dimensions) {
super();
if (this.vertices.length) {
throw new Error('Reinitializing geometry is not allowed');
}
this.position = Vector.from(position);
this.dimensions = Vector.from(dimensions);
// Next point is obtained by moving the specified length along each dimension
// one at a time, then reversing these movements in the same order.
let point = this.position;
for (let dim = dimensions.length - 1; dim >= 0; dim--) {
this.addVertex(point);
const increment = Vector.unitVector(dim, dimensions.length);
point = point.add(increment);
}
for (let dim = dimensions.length - 1; dim >= 0; dim--) {
this.addVertex(point);
const increment = Vector.unitVector(dim, dimensions.length);
point = point.subtract(increment);
}
}
get center() {
return Vector.from(this.dimensions.map((Q, idx) => this.position[idx] + Q / 2));
}
doesOverlap(rect) {
return this.dimensions.every((_, idx) => {
const thisMin = this.position[idx];
const thisMax = this.position[idx] + this.dimensions[idx];
const thatMin = rect.position[idx];
const thatMax = rect.position[idx] + rect.dimensions[idx];
return (thisMin <= thatMin && thisMax >= thatMin)
|| (thisMin >= thatMin && thisMin <= thatMax);
});
}
get aspectRatio() {
const [width, height] = this.dimensions;
return height / width;
}
}