The distance between two parallel lines will be the distance between the first (infinite) line and any point (say, P3) on the second line. Since you are working with coordinates, it's more convenient to use the vector representation of the formula than to try to express the line as an equation. Using that representation, in 2d this distance is given by |(P3 - P1) dot ( norm ( P2 - P1 ))|
, where norm
is a normalized perpendicular to P2 - P1
:
Also note, in 2d, a perpendicular to a vector (x, y)
is easily given by (-y, x)
. Thus:
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);
}
In production you will probably want to introduce some sort of Point
class which would beautify this API considerably, however since it isn't shown I wrote the code purely using doubles.