两条平行线之间的距离将是第一条(无限)线与第二条线上的任意点(例如 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);
}
在生产中,您可能想要引入某种Point 类,这将大大美化这个API,但是由于它没有显示,我纯粹使用双精度来编写代码。