Skip to content

Instantly share code, notes, and snippets.

@EduardoJM
Created July 11, 2020 18:11
Show Gist options
  • Save EduardoJM/8aa0948bf550dbe877f1c2e36d515efb to your computer and use it in GitHub Desktop.
Save EduardoJM/8aa0948bf550dbe877f1c2e36d515efb to your computer and use it in GitHub Desktop.
Separating Axis Theorem Collision Testing
polygon.testWith = function (otherPolygon) {
// get all edges
const edges = [];
for (let i = 0; i < polygon.edges.length; i++) {
edges.push(polygon.edges[i]);
}
for (let i = 0; i < otherPolygon.edges.length; i++) {
edges.push(otherPolygon.edges[i]);
}
// build all axis and project
for (let i = 0; i < edges.length; i++) {
// get axis
const length = Math.sqrt(edges[i].y * edges[i].y + edges[i].x * edges[i].x);
const axis = {
x: -edges[i].y / length,
y: edges[i].x / length,
};
// project polygon under axis
const { min: minA, max: maxA } = polygon.projectInAxis(axis.x, axis.y);
const { min: minB, max: maxB } = otherPolygon.projectInAxis(axis.x, axis.y);
if (intervalDistance(minA, maxA, minB, maxB) > 0) {
return false;
}
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment