silphius/app/ecs-components/collider.js

76 lines
2.1 KiB
JavaScript
Raw Normal View History

2024-07-02 16:16:39 -05:00
import Component from '@/ecs/component.js';
import {intersects} from '@/util/math.js';
import vector2d from './helpers/vector-2d';
export default class Collider extends Component {
instanceFromSchema() {
const {ecs} = this;
return class ColliderInstance extends super.instanceFromSchema() {
isCollidingWith(other) {
const {aabb, aabbs} = this;
const {aabb: otherAabb, aabbs: otherAabbs} = other;
if (!intersects(aabb, otherAabb)) {
return false;
}
for (const aabb of aabbs) {
for (const otherAabb of otherAabbs) {
if (intersects(aabb, otherAabb)) {
return true;
}
}
}
return false;
}
isWithin(query) {
const {aabb, aabbs} = this;
if (!intersects(aabb, query)) {
return false;
}
for (const aabb of aabbs) {
if (intersects(aabb, query)) {
return true;
}
}
return false;
}
recalculateAabbs() {
const {Position: {x: px, y: py}} = ecs.get(this.entity);
this.aabb = {x0: Infinity, x1: -Infinity, y0: Infinity, y1: -Infinity};
this.aabbs = [];
const {bodies} = this;
for (const points of bodies) {
let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
for (const point of points) {
const x = point.x + px;
const y = point.y + py;
if (x < x0) x0 = x;
if (x < this.aabb.x0) this.aabb.x0 = x;
if (x > x1) x1 = x;
if (x > this.aabb.x1) this.aabb.x1 = x;
if (y < y0) y0 = y;
if (y < this.aabb.y0) this.aabb.y0 = y;
if (y > y1) y1 = y;
if (y > this.aabb.y1) this.aabb.y1 = y;
}
this.aabbs.push({
x0: x0 > x1 ? x1 : x0,
x1: x0 > x1 ? x0 : x1,
y0: y0 > y1 ? y1 : y0,
y1: y0 > y1 ? y0 : y1,
});
}
}
}
}
static properties = {
bodies: {
type: 'array',
subtype: {
type: 'array',
subtype: vector2d('int16'),
},
},
};
}