空间上点到线段的最短距离

2019-11-14  本文已影响0人  宿州刘德华
/**
 * 点到线段的最短距离
 * @param a 线段一个点
 * @param b 线段另一个点
 * @param s 空间上任意一个点
 * @returns {number}
 */
 function point2LineDistance(a,b,s) {
    let ab = Math.sqrt(Math.pow((a.x - b.x), 2.0) + Math.pow((a.y - b.y), 2.0) + Math.pow((a.z - b.z), 2.0));
    let as = Math.sqrt(Math.pow((a.x - s.x), 2.0) + Math.pow((a.y - s.y), 2.0) + Math.pow((a.z - s.z), 2.0));
    let bs = Math.sqrt(Math.pow((s.x - b.x), 2.0) + Math.pow((s.y - b.y), 2.0) + Math.pow((s.z - b.z), 2.0));
    let cos_A = (Math.pow(as, 2.0) + Math.pow(ab, 2.0) - Math.pow(bs, 2.0)) / (2 * ab*as);
    let sin_A = Math.sqrt(1 - Math.pow(cos_A, 2.0));
    let t = ((a.x-s.x)*(a.x-b.x)+(a.y-s.y)*(a.y-b.y)+(a.z-s.z)*(a.z-b.z))/(Math.pow((a.x-b.x), 2.0)+Math.pow((a.y-b.y), 2.0)+Math.pow((a.z-b.z), 2.0));
    if(t<0){
        return as;
    }else if(t<=1&&t>=0){
        return as*sin_A;
    }else if(t>1){
        return bs;
    }
}

上一篇下一篇

猜你喜欢

热点阅读