Skip to content

Instantly share code, notes, and snippets.

@yiwenl
Last active September 5, 2023 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yiwenl/e4bb465c20e3508ffc5b5c249ee35ee0 to your computer and use it in GitHub Desktop.
Save yiwenl/e4bb465c20e3508ffc5b5c249ee35ee0 to your computer and use it in GitHub Desktop.
Triangle intersection check
// Triangle format: [[x, y], [x, y], [x, y]]
function doTrianglesIntersect(triangle1, triangle2) {
function doEdgesIntersect(edge1, edge2) {
// Check if two line segments (edges) intersect
const [x1, y1] = edge1[0];
const [x2, y2] = edge1[1];
const [x3, y3] = edge2[0];
const [x4, y4] = edge2[1];
const den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (den === 0) {
// Edges are parallel, no intersection
return false;
}
const t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den;
const u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den;
return t >= 0 && t <= 1 && u >= 0 && u <= 1;
}
// Calculate edges for both triangles
const edges1 = [
[triangle1[0], triangle1[1]],
[triangle1[1], triangle1[2]],
[triangle1[2], triangle1[0]],
];
const edges2 = [
[triangle2[0], triangle2[1]],
[triangle2[1], triangle2[2]],
[triangle2[2], triangle2[0]],
];
// Check for edge intersections
for (const edge1 of edges1) {
for (const edge2 of edges2) {
if (doEdgesIntersect(edge1, edge2)) {
return true; // Triangles intersect
}
}
}
return false; // Triangles do not intersect
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment