aabb-tree
Version:
Basic implementation of the AABB-Tree (Axis Aligned Box Bounding Tree)
65 lines (64 loc) • 2.1 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const AABB_1 = __importDefault(require("../AABB"));
class Polygon {
constructor(shape) {
this.shape = shape;
if (shape.length < 2) {
throw new Error('A polygon needs to have more than 2 sides');
}
let minX = Infinity;
let maxX = -Infinity;
let minY = Infinity;
let maxY = -Infinity;
shape.forEach(point => {
if (point.X < minX) {
minX = point.X;
}
if (point.X > maxX) {
maxX = point.X;
}
if (point.Y < minY) {
minY = point.Y;
}
if (point.Y > maxY) {
maxY = point.Y;
}
});
this.AABB = new AABB_1.default(minX, minY, null, maxX, maxY, null);
}
GetAABB() {
return this.AABB;
}
ContainsPoint(point) {
let hitCount = 0;
for (let i = 0; i < this.shape.length; i++) {
const point1 = this.shape[i];
const point2 = this.shape[(i + 1) % this.shape.length];
if (this.checkForHit(point1, point2, point)) {
hitCount++;
}
}
return hitCount > 0 && hitCount % 2 === 1;
}
checkForHit(point1, point2, rayStart) {
if (point1.Y <= point2.Y) {
if (rayStart.Y <= point1.Y || rayStart.Y > point2.Y || (rayStart.X >= point1.X && rayStart.X >= point2.X)) {
return false;
}
else if (rayStart.X < point1.X && rayStart.X < point2.X) {
return true;
}
else {
return (rayStart.Y - point1.Y) / (rayStart.X - point1.X) > (point2.Y - point1.Y) / (point2.X - point1.X);
}
}
else {
return this.checkForHit(point2, point1, rayStart);
}
}
}
exports.default = Polygon;