0

Possible Duplicate:
Find out if 2 lines intersect

If 2 lines are passed to a function, how can it deduce whether or not they're intersecting? Each line is in the form of 2 CPoint objects- so in total I have 4 points. The following is what I've come up with. It calculates the slopes and Y-intercepts of each line and calculates the intersection point from those. Then it checks whether the Intersection point lies on the segment; if yes it returns false; if no, i.e they dont intersect, it returns true. Though, it shows many problems. Is there an easier, more efficient way to do this?

NOTE : I wasn't very sure of what data types to use for the slopes and the Y-intercepts.

bool CShortestPathFinderDoc::edgeTest(CPoint P,CPoint P2,CPoint E,CPoint E2)
{
 bool status=true;
 double m1,m2;  //slopes
     double b1,b2;     //y-intercepts
 double y,x;     //intersection point

 m1=((double)P.y-P2.y)/((double)P.x-P2.x);   
 m2=((double)E.y - E2.y)/( (double)E.x - E2.x);    

 if(m1 == m2)    //if lines are colinear
    return true;


 b1=P.y-(m1*P.x)                         // Get the..
 b2=E->y - (m2*E.x);            //    Y-intercepts.

 x=(b2-b1)/(m1-m2);
 y=m1*x + b1;         //x,y is the intersection point!!!

 if((x<P2.x && x>P.x))             //if intersection point lies on line!!!!!
  {
    if(P2.y > P.y)
        if(y<P2.y && y>P.y)
            status=false;
            if(P2.y < P.y)
        if(y<P.y && y>P2.y)
                status=false;       
  }

 return status;
 }
Community
  • 1
  • 1
Ghost
  • 1,777
  • 6
  • 31
  • 44

2 Answers2

0

Wolfram has everything you need, specifically Line-Line Distance, i.e. distance between lines. If line is zero (+-epsilon) then they intersect.

Skizz
  • 69,698
  • 10
  • 71
  • 108
0

Line segment intersection is what you are looking for. Perhaps you can adapt the sweep line algorithm for your need.

BTW: In your code snippet above, in order to find out whether two 2D lines are parallel, you only have to compute scalar product from vectors defined by the input points.

Marko
  • 21
  • 5