Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@1j01 1j01 commented May 17, 2016

You can just return (s >= 0 && s <= 1 && t >= 0 && t <= 1);

@sashuk

This comment has been minimized.

Copy link

@sashuk sashuk commented Jun 13, 2016

Thanks a lot

@TerryHibbert

This comment has been minimized.

Copy link

@TerryHibbert TerryHibbert commented Feb 10, 2017

This is great. Thanks!

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