求空间中线段上到已知直线距离最近的点

这篇博客介绍了如何求解空间中线段上到已知直线的最近距离问题,提供了相应的数学分析和Ogre::Vector3的C++实现。通过计算参数t来确定最近点在线段上的位置,并处理了平行线段的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个其实是求线段到直线之间的最近距离,求出最近距离位置在线段上的点。
如下图所示,一条线段和一条直线的解的限定区域为[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时为线段的终止点。

参考《计算机图形学几何工具算法详解》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值