如何找到两个平行线段之间的垂直距离?

baa*_*aal 2 c++ parallel-processing geometry lines euclidean-distance

我有许多平行线段,例如L1(P1,P2)和L2(P3,P4)。这些点分别具有x和y坐标。这些平行线段的角度在0-180度之间。

如何有效地在c ++中找到这些线段之间的垂直空间? 两个平行线段之间的距离

dbc*_*dbc 5

两条平行线之间的距离将是第一条(无限)线与第二条线上的任意点(例如P3)之间的距离。由于正在使用坐标,因此使用公式的矢量表示比尝试将线表示为方程式更为方便。使用该表示法,在2d中,此距离由给出|(P3 - P1) dot ( norm ( P2 - P1 ))|,其中norm垂直于P2 - P1

在此处输入图片说明

还要注意,在2d中,(x, y)很容易给出与向量的垂直方向(-y, x)。从而:

class GeometryUtilities
{
public:
    GeometryUtilities();
    ~GeometryUtilities();

    static double LinePointDistance2D(double lineP1X, double lineP1Y, double lineP2X, double lineP2Y, double pointX, double pointY);

    static void Perpendicular2D(double x, double y, double &outX, double &outY);

    static double Length2D(double x, double y);
};

double GeometryUtilities::LinePointDistance2D(double lineP1X, double lineP1Y, double lineP2X, double lineP2Y, double pointX, double pointY)
{
    double vecx = lineP2X - lineP1X;
    double vecy = lineP2Y - lineP1Y;
    double lineLen = Length2D(vecx, vecy);
    if (lineLen == 0.0) // Replace with appropriate epsilon
    {
        return Length2D(pointX - lineP1X, pointY - lineP1Y);
    }

    double normx, normy;
    Perpendicular2D(vecx/lineLen, vecy / lineLen, normx, normy);
    double dot = ((pointX - lineP1X) * normx + (pointY - lineP1Y) * normy); // Compute dot product (P3 - P1) dot( norm ( P2 - P1 ))
    return abs(dot);
}

void GeometryUtilities::Perpendicular2D(double x, double y, double &outX, double &outY)
{
    outX = -y;
    outY = x;
}

double GeometryUtilities::Length2D(double x, double y)
{
    return sqrt(x*x + y*y);
}
Run Code Online (Sandbox Code Playgroud)

在生产中,您可能想要引入某种Point可以大大美化此API 的类,但是由于未显示,因此我仅使用双精度代码编写了代码。