We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › Line segment intersections
Page Index Toggle Pages: 1
Line segment intersections (Read 615 times)
Line segment intersections
Mar 2nd, 2006, 12:59am
 
I'd like to test two line segments to see if they intersect. I have read about the Sweep algorithm but I think it's overkill for what I'd like to do. Any thoughts? Google is surprisingly sparse on the topic.
Re: Line segment intersections
Reply #1 - Mar 2nd, 2006, 1:11am
 
http://astronomy.swin.edu.au/~pbourke/geometry/lineline2d/

Seems to help. Nevermind!
Re: Line segment intersections
Reply #2 - Mar 3rd, 2006, 6:22am
 
Also look for Sedgewick's line line intersection. He uses a counterclockwise clockwise routine.
Re: Line segment intersections
Reply #3 - Mar 4th, 2006, 12:15pm
 
Here it is. Although you'll have to rip out the implementation of my personal vector library inside it.

Code:

//Sedgwick's Line Intersection algorithm
//Will return 1 if p1 to p2 to p3 is found to be rotating counter clockwise
int CCW(vec2 p1, vec2 p2, vec2 p3)
{
float dx1, dx2, dy1, dy2;
dx1 = p2.x - p1.x;
dy1 = p2.y - p1.y;
dx2 = p3.x - p1.x;
dy2 = p3.y - p1.y;
if (dx1*dy2 > dy1*dx2) return +1;
if (dx1*dy2 < dy1*dx2) return -1;
if ((dx1*dx2 < 0) || (dy1*dy2 < 0)) return -1;
if ((dx1*dx1+dy1*dy1) < (dx2*dx2+dy2*dy2))
return +1;
return 0;
}



//Given lines A1A2, B1B2, this returns true if they are intersecting
boolean intersect(vec2 a1, vec2 a2, vec2 b1, vec2 b2)
{
return
((CCW(a1, a2, b1) != CCW(a1, a2, b2))
&& (CCW(b1, b2, a1) != CCW(b1, b2, a2)));
}

//Given line segment A and B, returns true if found intersecting
boolean intersect(seg a,seg b)
{
if(a==null||b==null)
return false;
vec2 a1=a.a;
vec2 a2=a.b;
vec2 b1=b.a;
vec2 b2=b.b;
return intersect(a1,a2,b1,b2);
}

Page Index Toggle Pages: 1