2015-01-26 124 views
2

我需要能够找到由两个点定义的两条线之间的交点。我有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个功能更好的方法,请告诉我。我愿意接受任何解决方案。

编辑: 这两条线是有界的点;他们不是无限的。

+2

您可以从[Wikipedia](http://en.wikipedia.org/wiki/Line%E2%80%93line_intersection)获取函数的逻辑。如果您在将逻辑转换为代码时遇到困难,请回到相关问题。 – 2015-01-26 19:21:50

+0

我投票结束这个问题作为题外话,因为它要求[代码评论](http://codereview.stackexchange.com/) – 2015-01-26 19:24:00

+1

有许多重复和接近重复,例如:http:// stackoverflow .com/q/563198/179910和http://stackoverflow.com/q/14176776/179910。 – 2015-01-26 19:24:55

回答

3

计算的交点值,可以通到一个线对的交叉点计算:

/// A factor suitable to be passed to line \arg a as argument to calculate 
/// the intersection point. 
/// \NOTE A value in the range [0, 1] indicates a point between 
/// a.p() and a.p() + a.v(). 
/// \NOTE The result is std::numeric_limits<double>::quiet_NaN() if the 
/// lines do not intersect. 
/// \SEE intersection_point 
inline double intersection(const Line2D& a, const Line2D& b) { 
    const double Precision = std::sqrt(std::numeric_limits<double>::epsilon()); 
    double d = a.v().x() * b.v().y() - a.v().y() * b.v().x(); 
    if(std::abs(d) < Precision) return std::numeric_limits<double>::quiet_NaN(); 
    else { 
     double n = (b.p().x() - a.p().x()) * b.v().y() 
       - (b.p().y() - a.p().y()) * b.v().x(); 
     return n/d; 
    } 
} 

/// The intersection of two lines. 
/// \NOTE The result is a Point2D having the coordinates 
///  std::numeric_limits<double>::quiet_NaN() if the lines do not 
///  intersect. 
inline Point2D intersection_point(const Line2D& a, const Line2D& b) { 
    // Line2D has an operator() (double r) returning p() + r * v() 
    return a(intersection(a, b)); 
} 

注:P()是线和v的原点()的矢量到终点= p()+ v()

+0

我对标量不熟悉。我将如何创建一个标量,然后将其传递给您提供的函数? – 2015-01-26 19:42:50