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;
}