Skip to content

Instantly share code, notes, and snippets.

@Joncom
Last active September 11, 2021 00:29
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Joncom/e8e8d18ebe7fe55c3894 to your computer and use it in GitHub Desktop.
Save Joncom/e8e8d18ebe7fe55c3894 to your computer and use it in GitHub Desktop.
Check if two line segments intersect
// Adapted from: http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect/1968345#1968345
function line_intersects(p0_x, p0_y, p1_x, p1_y, p2_x, p2_y, p3_x, p3_y) {
var s1_x, s1_y, s2_x, s2_y;
s1_x = p1_x - p0_x;
s1_y = p1_y - p0_y;
s2_x = p3_x - p2_x;
s2_y = p3_y - p2_y;
var s, t;
s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);
t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
{
// Collision detected
return 1;
}
return 0; // No collision
}
@1j01
Copy link

1j01 commented May 17, 2016

You can merge the two returns into return (s >= 0 && s <= 1 && t >= 0 && t <= 1);

@sashuk
Copy link

sashuk commented Jun 13, 2016

Thanks a lot

@TerryHibbert
Copy link

This is great. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment