Skip to content

Instantly share code, notes, and snippets.

@coleww
Last active August 29, 2015 13:57
Show Gist options
  • Save coleww/9403691 to your computer and use it in GitHub Desktop.
Save coleww/9403691 to your computer and use it in GitHub Desktop.
Do two lines intersect? Processing/Java
//adapted from http://wiki.processing.org/w/Line-Line_intersection
//I do not understand how or why this works.
boolean intersects(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) {
float bx = x2 - x1;
float by = y2 - y1;
float dx = x4 - x3;
float dy = y4 - y3;
float b_dot_d_perp = bx * dy - by * dx;
if (b_dot_d_perp == 0) {
return false;
}
float cx = x3 - x1;
float cy = y3 - y1;
float t = (cx * dy - cy * dx) / b_dot_d_perp;
if (t < 0 || t > 1) {
return false;
}
float u = (cx * by - cy * bx) / b_dot_d_perp;
if (u < 0 || u > 1) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment