找到由2个点定义的2条线的交点

时间:2015-01-26 19:14:44

标签: c++ intersection

我需要能够找到两条线之间的交点,每条线由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;
}

注意: 如果一条或所有线是垂直的并且线条在彼此的顶部,则该功能必须能够工作。因此,代码可能无法使用y = m * x + b形式,因为垂直线除以0错误。

如果有更好的方法比使用2个功能更好,请告诉我。我愿意接受任何解决方案。

修改 这两条线以点为界;它们不是无限的。

1 个答案:

答案 0 :(得分: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()