I need to be able to find the intersection between two lines defined by 2 points each. I have 2 functions; one to calculate if there is an intersection between two lines, and on to determine the point of intersection of those lines. Please respond with some possible code for each function.
Code structure so far:
struct Pos
{
float x;
float y;
};
struct Line
{
Pos Pos1;
Pos Pos2;
};
bool Collide(Line Line1, Line Line2)
{
return true;// Return if there is an intersection
}
Pos CollidePoint(Line Line1, Line Line2)
{
return {0, 0};// return the point of intersection
}
int main()
{
Line Line1 = { { 10, 20 }, { 20, 20 } };// Define one line
Line Line2 = { { 5, 30 }, { 15, 15 } };// Define another line
if (Collide(Line1, Line2))//check if a collision exists
{
//Display the point of intersection
cout << "X:" << CollidePoint(Line1, Line2).x << " Y:" << CollidePoint(Line1, Line2).y << endl;
}
else
{
//If there is no collision
cout << "No Collision" << endl;
}
return 0;
}
NOTE: The function has to be able to work if one or all the lines are vertical and if the lines are on top of each other. Because of this, the code probably won't work with the form y=m*x+b due to the divide by 0 error with vertical lines.
If there is a better way to do this than using the 2 functions please tell me. I'm open to any solution.
EDIT: The two lines are bounded by the points; they are not infinite.