Three Js 疑难问题:解决点到线段最短距离的问题
程序员文章站
2022-07-14 19:39:45
...
求解点到线段最短距离的问题的方案如下:
/*
x pt
x | |
x | |
x | |
x | |
x | |
x | |
x | | --> Vector = (pt - targetPt), distance = |pt-targetPt|
x | |
x | |
x | |
x | |
x aaa@qq.com | |
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 aaa@qq.com 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 aaa@qq.com 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
},
这里需要注意的是,必须保证垂直距离下来的点必须落在红线之上。
具体效果如下:
去掉三角形两边的线之后的效果入下:
下一篇: json字符串中获取数据