如何用JavaScript高效查找三维空间中距离目标点最近的坐标点,以及判断该点在线段的哪个位置?

聖光之護
发布: 2025-02-26 19:02:10
原创
293人浏览过

如何用JavaScript高效查找三维空间中距离目标点最近的坐标点,以及判断该点在线段的哪个位置?

本文提供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方法控制精度:

立即学习Java免费学习笔记(深入)”;

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高效查找三维空间中距离目标点最近的坐标点,以及判断该点在线段的哪个位置?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号