Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this line-intersection work?

Tags:

c++

math

I'm building an Asteroids Game for a class assignement. To finish it I need a line-intersection algorithm/code. I found one that works, but i do not understand the math behind it. How does this work?

point* inter( point p1, point p2, point p3, point p4)
{
point* r;

//p1-p2 is the first edge. 
//p3-p4 is the second edge.
r = new point;
float x1 = p1.x, x2 = p2.x, x3 = p3.x, x4 = p4.x;
float y1 = p1.y, y2 = p2.y, y3 = p3.y, y4 = p4.y;

//I do not understand what this d represents.
float d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
// If d is zero, there is no intersection
if (d == 0) return NULL;

// I do not understand what this pre and pos means and
// how it's used to get the x and y of the intersection
float pre = (x1*y2 - y1*x2), pos = (x3*y4 - y3*x4);
float x = ( pre * (x3 - x4) - (x1 - x2) * pos ) / d;
float y = ( pre * (y3 - y4) - (y1 - y2) * pos ) / d;

// Check if the x and y coordinates are within both lines
if ( x < min(x1, x2) || x > max(x1, x2) ||
        x < min(x3, x4) || x > max(x3, x4) ) return NULL;
if ( y < min(y1, y2) || y > max(y1, y2) ||
        y < min(y3, y4) || y > max(y3, y4) ) return NULL;

cout << "Inter X : " << x << endl;
cout << "Inter Y : " << y << endl;

// Return the point of intersection
r->x = x;
r->y = y;
return r; 
}
like image 809
Alessandro Stamatto Avatar asked Sep 10 '26 20:09

Alessandro Stamatto


1 Answers

Determining the intersection of two lines in a two-dimensional plane, if any (they could be parallel) is a classical math problem. The algorithm you found is based on solving a system with two linear equations. This is done by computing the determinant (d). If zero, then the lines are parallel. Otherwise the point of intersection is computed.

See for example this tutorial for a detailed description of the formula: http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry2

like image 178
Kim Burgaard Avatar answered Sep 13 '26 09:09

Kim Burgaard