blaze-2d
Version:
A fast and simple WebGL 2 2D game engine written in TypeScript
93 lines • 3.21 kB
JavaScript
import { vec2 } from "gl-matrix";
import GJK from "../gjk";
import EPA from "../epa";
import Line from "../../shapes/line";
/**
* Represents a box in 2D space with a position and dimensions.
*/
export default class LineCollider extends Line {
/**
* Checks if this line is colliding with another collider.
*
* @param c {@link Collider} to test collisions against
* @returns {@link CollisionResult} with the results of the test
*/
testCollision(c) {
const res = {
normal: undefined,
depth: undefined,
hasCollision: false,
};
const gjkRes = GJK(this, c);
if (!gjkRes.collision)
return res;
res.hasCollision = true;
const epaRes = EPA(gjkRes.simplex, this, c);
res.normal = epaRes.normal;
res.depth = epaRes.depth;
return res;
}
/**
* Calculates a support point on the minkowski difference in a given direction.
*
* @param c The collider to test against
* @param direction The direction to use when calculating furthest points
* @returns The support point in the given direction for the [Minkowski difference](https://en.wikipedia.org/wiki/Minkowski_addition)
*/
supportPoint(c, direction) {
const p = vec2.create();
const reverse = vec2.create();
vec2.scale(reverse, direction, -1);
vec2.sub(p, this.findFurthestPoint(direction), c.findFurthestPoint(reverse));
return p;
}
/**
* Calculates the furthest point on the collider in a direction.
*
* @param direction The direction in which to calculate the furthest point
* @returns The furthest point on the collider in the given direction
*/
findFurthestPoint(direction) {
const points = this.getPoints();
let max;
let maxDist = -Infinity;
for (const p of points) {
const dist = vec2.dot(p, direction);
if (dist > maxDist) {
maxDist = dist;
max = p;
}
}
return max;
}
/**
* Calculates the furthest point on the collider in a direction and it's neighbouring vertices on the collider.
*
* @param direction The direction in which to calculate the furthest point
* @returns The furthest point on the collider in the given direction and its left and right neighbours
*/
findFurthestNeighbours(direction) {
const points = this.getPoints();
let max = 0;
let maxDist = -Infinity;
for (let i = max; i < points.length; i++) {
const p = points[i];
const dist = vec2.dot(p, direction);
if (dist > maxDist) {
maxDist = dist;
max = i;
}
}
const leftIndex = max + 1 >= points.length ? 0 : max + 1;
const rightIndex = max - 1 < 0 ? points.length - 1 : max - 1;
return {
furthest: points[max],
left: points[leftIndex],
right: points[rightIndex],
furthestIndex: max,
leftIndex,
rightIndex,
};
}
}
//# sourceMappingURL=line.js.map