求点到直线的垂足

本文介绍了一种计算三维空间中点到直线的垂足的方法。通过构建坐标系,利用向量运算和矩阵变换,实现了从任意点找到其在指定直线上的垂直投影点。文章详细解释了判断点是否在直线上和平行的特殊情况处理。

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

    /// <summary>
    /// 计算点到直线的垂足
    /// </summary>
    /// <param name="lineP1">直线起点</param>
    /// <param name="lineP2">直线终点</param>
    /// <param name="point">待求的点</param>
    /// <returns></returns>
    public static double[] CalPerpendicularPoint(double[] lineP1,double[] lineP2,double[] point)
    {
        UFSession theUfSession = UFSession.GetUFSession();
        double[] perpendicularPoint = new double[3];
        //如果point和p1构成的矢量和直线平行则point在直线上
        double[] vecPoint = new double[3];
        theUfSession.Vec3.Sub(point, lineP1, vecPoint);
        double[] vecLine = new double[3];
        theUfSession.Vec3.Sub(lineP2, lineP1, vecLine);
        int isParallel;
        theUfSession.Vec3.IsParallel(vecPoint, vecLine, 0.0001, out isParallel);
        if (isParallel==1/*0不平行,1平行*/)
        {
            perpendicularPoint = (double[])point.Clone();
            return perpendicularPoint;
        }

        //由lineP1,lineP2,point构建坐标系,lineP1为原点,lineP2为X点,三点法向为Z向
        double[] xVec = vecLine;
        double[] origin = lineP1;
        double[] zVec = new double[3];
        theUfSession.Vec3.Cross(xVec, vecPoint, zVec);
        double[] yVec = new double[3];
        theUfSession.Vec3.Cross(zVec, xVec, yVec);
        double mag;
        theUfSession.Vec3.Unitize(xVec, 0.0001, out mag, xVec);//归一
        theUfSession.Vec3.Unitize(yVec, 0.0001, out mag, yVec);
        theUfSession.Vec3.Unitize(zVec, 0.0001, out mag, zVec);
        double[] trans1 = new double[]
        {
            xVec[0],yVec[0],zVec[0],origin[0],
            xVec[1],yVec[1],zVec[1],origin[1],
            xVec[2],yVec[2],zVec[2],origin[2],
            0,0,0,1
        };
        double[] trans2 = new double[16];
        theUfSession.Mtx4.Invert(trans1, trans2);
        theUfSession.Mtx4.Vec3Multiply(point, trans2, perpendicularPoint);
        perpendicularPoint[1] = 0;
        theUfSession.Mtx4.Vec3Multiply(perpendicularPoint, trans1, perpendicularPoint);
        return perpendicularPoint;
    }

 

转载于:https://my.oschina.net/hitbangmaker/blog/883668

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值