javascript - 如何计算多个航点之间的航点?
问题描述
例如,我有一个包含 3 个航点的数组:
[ [ 526, 1573, 24 ], [ 2224, 809, -1546 ], [ 6869, 96, -3074 ] ]
我也知道我想休息让我们说n
到达第一个和最后一个航路点之间的时间。所以最后我想要一个n
点数组。
我如何n
在 JS 中找到那些休息点?
提前致谢!
编辑:注意这不是一个单一的对象!想象每个轴都是一个人。他们必须在相同的时间和相同的时间停止,但显然他们不必在同一个地方。
解决方案
您想使用线性插值。
一个简单的例子:
const POINTS = [ [ 526, 1573, 24 ], [ 2224, 809, -1546 ], [ 6869, 96, -3074 ] ];
const N = 10;
function getDistance(point1, point2) {
// speed in 3d space is mutated according only to the X distance,
// to keep speed constant in X dimension
return Math.abs(point1[0] - point2[0]);
}
function go(points, n) {
const pointDistances = points.slice(1).map((point, index) => getDistance(points[index], point));
const fullDistance = pointDistances.reduce((sum, distance) => sum + distance, 0);
const distancePerSection = fullDistance / n;
return points.slice(1)
.reduce((last, point, index) => {
const thisDistance = pointDistances[index];
const numRestPoints = Math.max(0, Math.floor(thisDistance / distancePerSection) - 1);
if (!numRestPoints) {
return last.concat([point]);
}
const thisYVector = point[1] - points[index][1];
const thisZVector = point[2] - points[index][2];
return last.concat(new Array(numRestPoints).fill(0)
.reduce((section, item, restIndex) => {
return section.concat([[
points[index][0] + (restIndex + 1) * distancePerSection,
points[index][1] + (restIndex + 1) * thisYVector * distancePerSection / thisDistance,
points[index][2] + (restIndex + 1) * thisZVector * distancePerSection / thisDistance
]]);
}, [])
.concat([point])
);
}, points.slice(0, 1));
}
function test() {
const result = go(POINTS, N);
if (result.length !== N) {
throw new Error('Must be N length');
}
if (!result[0].every((value, index) => value === POINTS[0][index])) {
throw new Error('Doesn\'t start at the first point');
}
if (!result[N - 1].every((value, index) => value === POINTS[POINTS.length - 1][index])) {
throw new Error('Doesn\'t end at the last point');
}
if (!POINTS.slice(1, N - 1).every(point =>
result.some(resultPoint => resultPoint.every((value, index) => value === point[index]))
)) {
throw new Error('Doesn\'t go through every provided point');
}
console.log(result.slice(1).map((point, index) => getDistance(point, result[index])));
console.log('The result passed the tests!');
console.log(JSON.stringify(result, null, 2));
}
test();
我基本上是在浏览点列表,并确定它们之间是否应该存在任何休息点,如果存在则插入它们。
如果您想进一步澄清,请发表评论!
推荐阅读
- google-apps-script - 使用 onChange 检测 Note 更改
- microsoft-graph-api - 从 Microsoft 团队频道获取所有消息和回复 - 图表分页
- c# - 是否可以从 MVVM 弹出 DisplayPromptAsync
- javascript - Javascript 循环值显示为未定义
- php - 将自定义设置添加到 WooCommerce 产品选项卡
- stripe-payments - 条带连接帐户订阅
- vba - 根据单击更改文本框的前景色,并在单击另一个文本框时将其返回到以前的前景色?
- c# - 将每个属性序列化为字节数组
- sql - 在 SQL 查询中重复元组
- spring - Spring集成中如何处理嵌套事务异常