如何用JavaScript高效查找三维空间中距离目标点最近的坐标点,以及判断该点在线段的哪个位置?(中距离.线段.高效.如何用.查找.....)
wufei123 2025-03-01 阅读:57 评论:0本文提供javascript解决方案,高效解决两个三维空间几何问题:一、查找距离目标点最近的坐标点;二、判断目标点在线段的哪个位置。
一、寻找最近坐标点
给定目标点[x, y, z]和一个包含多个三维坐标点的数组,需找到距离目标点最近的坐标点及其索引。 我们采用欧几里得距离计算,并使用reduce方法优化查找效率:
const target = [-11.034364525537594, 1, 24.978631454302235];
const arr = [
[-4.167605156499352, 1, 16.43419792128068],
[-13.60939928892453, 1, 28.216932747654095],
[-16.84770058227477, 1, 27.514650539457307]
];
const nearestPoint = arr.reduce((nearest, point, index) => {
const distanceSquared = point.reduce((sum, coord, i) => sum + Math.pow(coord - target[i], 2), 0);
if (index === 0 || distanceSquared < nearest.distanceSquared) {
return { point, index, distanceSquared };
}
return nearest;
}, { distanceSquared: Infinity });
console.log("Nearest point:", nearestPoint.point, "Index:", nearestPoint.index);
二、判断点在线段位置
判断三维坐标点是否位于给定线段上,需要运用空间向量中的三点共线判断。 为避免浮点数精度问题,我们使用toFixed方法控制精度:
function isCollinear(p1, p2, p3, precision = 10) {
const fixed = num => parseFloat(num.toFixed(precision));
return fixed((p2[1] - p1[1]) * (p3[0] - p2[0])) === fixed((p3[1] - p2[1]) * (p2[0] - p1[0])) &&
fixed((p2[2] - p1[2]) * (p3[0] - p2[0])) === fixed((p3[2] - p2[2]) * (p2[0] - p1[0])) &&
fixed((p2[2] - p1[2]) * (p3[1] - p2[1])) === fixed((p3[2] - p2[2]) * (p2[1] - p1[1]));
}
function findSegmentPosition(point, segment) {
if (isCollinear(segment[0], segment[1], point)) {
//Further checks to determine exact position on the segment could be added here if needed (e.g., using dot product).
return "On segment";
}
return "Not on segment";
}
const segment = [[-5, 0, 10], [5, 0, 20]];
const pointOnSegment = [0, 0, 15];
const pointOffSegment = [0, 10, 15];
console.log(findSegmentPosition(pointOnSegment, segment)); // Output: On segment
console.log(findSegmentPosition(pointOffSegment, segment)); // Output: Not on segment
以上代码提供了更清晰、更易于理解的函数,并对精度问题进行了处理,提高了代码的鲁棒性。 isCollinear 函数可以根据需要调整精度参数 precision。 findSegmentPosition 函数目前仅判断点是否在线段上, 可以根据需求扩展,例如计算点在线段上的比例位置等。
以上就是如何用JavaScript高效查找三维空间中距离目标点最近的坐标点,以及判断该点在线段的哪个位置?的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论