Hi, i think that this algorithm can be improved by looking for the x coordinate of the intersection if it exist (if the lines aren't parallels). Then you need no more than a test to see if it belongs to one of the lines. I would give something like:
bool vec2LinesIntersect ( Vector2 l1s, Vector2 l1f, Vector2 l2s, Vector2 l2f ) { // the two lines are defined by the following equations // (L1) y = m1*x + p1 // (L2) y = m2*x + p2 Real m1 = (l1f.y - l1s.y) / (l1f.x - l1s.x), m2 = (l2f.y - l2s.y) / (l2f.x - l2s.x); if ( m1 == m2) // the two lines are parallels return false; // now calculates the x coordinate of the intersection point (which exist m1 != m2) Real interX = ( (l2s.y - m2*l1s.x) - (l1s.y - m1*l1s.x) ) / (m1 - m2); // the intercection belongs to the first line so a real k such as // the vector [l1s,l1f] equals k*[l1s,inter] exists if ( interX == l1s.x ) // the intersection point is the l1s point return true; Real k = (l1f.x - l1s.x) / (interX - l1s.x); // now verify if the intersection belong to the line area return ( k >= 0 && k<=1 ); }
Proposal doesn't work
Your proposal doesn't work:
1. m1 and m2 can be invalid due to division by zero problems.
2. interX doesn't always fit
3. probably some more (not sure though)