我需要能够找到由两个点定义的两条线之间的交点。我有2个功能;一个用于计算两条线之间是否存在交叉点,另一个用于确定这些线的交点。请为每个功能提供一些可能的代码。查找由2个点定义的2条线的交点
代码结构至今:
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;
}
注: 功能必须能够,如果一个工作或所有的线是垂直,如果线在彼此的顶部。正因为如此,由于用垂直线除以0误差,代码可能不会与y = m * x + b形式一起工作。
如果有比使用2个功能更好的方法,请告诉我。我愿意接受任何解决方案。
编辑: 这两条线是有界的点;他们不是无限的。
您可以从[Wikipedia](http://en.wikipedia.org/wiki/Line%E2%80%93line_intersection)获取函数的逻辑。如果您在将逻辑转换为代码时遇到困难,请回到相关问题。 – 2015-01-26 19:21:50
我投票结束这个问题作为题外话,因为它要求[代码评论](http://codereview.stackexchange.com/) – 2015-01-26 19:24:00
有许多重复和接近重复,例如:http:// stackoverflow .com/q/563198/179910和http://stackoverflow.com/q/14176776/179910。 – 2015-01-26 19:24:55