这个其实是求线段到直线之间的最近距离,求出最近距离位置在线段上的点。
如下图所示,一条线段和一条直线的解的限定区域为[0, 1] ×[-∞, ∞]。假设直线为直线L_1 (s)=P_1+s(d_1 ) ⃗,则线段对应直线方程L_2(s)=P_2+t(d_2 ) ⃗中t的范围为[0, 1]。如果在线段所在的无限直线上的最接近点的参数小于0或者大于1,那么就必须在线段的一端取得最近的点,即为线段一端的端点。
根据上面的分析,线段上到直线距离最近的点为:(源码)
Ogre::Vector3 getClosestPointOnSegment(const Ogre::Vector3& lineBase,const Ogre::Vector3& lineDirection, const Ogre::Vector3& segmentBase,const Ogre::Vector3& segmentEnd)
{
Ogre::Vector3 segmentDirection = segmentEnd - segmentBase;
Ogre::Vector3 u = lineBase - segmentBase;
Ogre::Real a = lineDirection.dotProduct(lineDirection);
Ogre::Real b = lineDirection.dotProduct(segmentDirection);
Ogre::Real c =segmentDirection.dotProduct(segmentDirection);
Ogre::Real d = lineDirection.dotProduct(u);
Ogre::Real e = segmentDirection.dotProduct(u);
Ogre::Real det = a*c - b*b;
Ogre::Real tDenom = det;
Ogre::Real tNum;
// check for (near) parallelism
if (det < FLT_EPSILON)
{
// choose base point of the segmentif its direction is same direction of line
if(segmentDirection.directionEquals(lineDirection,Ogre::Radian(Ogre::Math::PI/10)))
{
returnsegmentBase;
}
else
{
returnsegmentEnd;
}
}
else
{
// Find parameter values ofclosest points on each segment's infinite line.
// Denominator assumed at this pointto be "det", which is always positive.
tNum = a*e - b*d;
}
// check value of numerators to see if we're outside the[0,1],[0,1] domain
if (tNum < 0)
{
return segmentBase; // t = 0;
}
else if (tNum > tDenom)
{
return (segmentBase +segmentDirection); //t = 1; because tNum = tDenom
}
else
{
// parameters of nearest points onrestricted domain
return (segmentBase + tNum/tDenom *segmentDirection); // t = tNum / tDenom;
}
}
其中当t小于0时,取t的值为0;当t大于1时,取t的值为1. 其中t为0时是线段的起始点,t为1时为线段的终止点。
参考《计算机图形学几何工具算法详解》