【问题标题】:Finding the intersection of 2 lines defined by 2 points [duplicate]找到由 2 个点定义的 2 条线的交点 [重复]
【发布时间】: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 个函数更好的方法,请告诉我。我愿意接受任何解决方案。

编辑: 两条线以点为界;它们不是无限的。

【问题讨论】:

标签: c++ intersection


【解决方案1】:

计算一个交点值,您可以将其传递给一条线进行交点计算:

/// 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()

【讨论】:

  • 我不熟悉标量。我将如何创建一个标量,然后将其传递给您提供的函数?
猜你喜欢
  • 1970-01-01
  • 2011-01-11
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多