Three Js 疑难问题:解决点到线段最短距离的问题

求解点到线段最短距离的问题的方案如下:


      /*
                                  x pt
                                x   |         |
                              x     |         |
                            x       |         |
                          x         |         |
                        x           |         |
                      x             |         |
                    x               |         | --> Vector = (pt - targetPt), distance = |pt-targetPt|
                  x                 |         |
                x                   |         |
              x                     |         |
            x                       |         |
          x    cost@                |         |
          pt1----------pt2          targetPt     warningPt

      */
      calculateDistance(pt1, pt2, pt) {
        const egdeV1 = new Vector3().subVectors(pt2, pt1)
        const egdeV2 = new Vector3().subVectors(pt, pt1)

        // translate to normalize
        const v1Norm = egdeV1.clone().normalize()
        const v2Norm = egdeV2.clone().normalize()
        // calculate the cos@ between vector 1 and vector 2
        const cos1 = v1Norm.dot(v2Norm)

        const egdeV3 = new Vector3().subVectors(pt, pt2)
        const egdeV4 = new Vector3().subVectors(pt1, pt2)
        const v3Norm = egdeV3.clone().normalize()
        const v4Norm = egdeV4.clone().normalize()
        // calculate the cos@ between vector 1 and vector 2
        const cos2 = v3Norm.dot(v4Norm)

        // make sure to angel are less than 90, the distance will be located at red line
        if (cos2 > 0 && cos1 > 0) {

          const sin = Math.sqrt(1 - cos1 * cos1)

          const yDistance = pt1.distanceTo(pt)
          const distance = yDistance * sin

          // calculate target point
          const xDistance = yDistance * cos1
          const dir = egdeV1.clone().normalize().multiplyScalar(xDistance)
          const targetPt = pt1.clone().add(dir)

          const warningDir = egdeV1.clone().normalize().multiplyScalar(xDistance + 200)
          const warningPt = pt1.clone().add(warningDir)

          return {'pt1': pt1, 'pt2': pt2, 'pt': pt, 'distance': distance, 'targetPt': targetPt, 'warningPt': warningPt}
        }

        return null
      },

这里需要注意的是,必须保证垂直距离下来的点必须落在红线之上。

 

具体效果如下:

 

去掉三角形两边的线之后的效果入下:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值