【发布时间】:2015-01-26 19:14:44
【问题描述】:
我需要能够找到由 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获取函数的逻辑。如果您在将逻辑转换为代码时遇到问题,请返回相关问题。
-
我投票结束这个问题,因为它要求Code Review
标签: c++ intersection