【问题标题】:Calculator distance between two points after move x steps移动 x 步后两点之间的计算器距离
【发布时间】:2021-03-12 19:33:32
【问题描述】:

我有static目的地点(x2, y2),动态点(x1, y1)需要到达目的地。

每一轮我都会得到 dynamic 点的 x 步,我需要在它进行 x 步后计算新的动态点 (x1, y1)。

我有两点之间的距离:

const distance = Math.hypot(x2 - x1, y2 - y1);

但是需要在到达目的地的步骤之后计算新的(x1, y1),我怎样才能通过这个公式完成呢?

例如:

point1 = (x1, y1) = (100, 100)

point2 = (x2, y2) = (400, 400)

距离 = ~424

现在point1向point2方向直线移动“30”步,意思是现在的距离是(distance - 30)我想?,什么是新的(x1,y1)?

【问题讨论】:

  • 问题不清楚。你能举个例子吗?
  • 好的,现在添加它
  • 计算方向和新位置。 direction 是 [x2, y2] - [x1, y1]。这个方向的unitVector 是direction / |direction|。新职位是[x1, y1] + 30 * unitVector。
  • 在你的例子中,单位向量是[1, 1] / sqrt(2) = [0.707..., 0.707...]。新职位是[121.213..., 121.213...]。您可以计算新的距离。这是~394。
  • 我们在谈论向量。 unitVector、[x2, y2]、[x1, y1] 和 [x2, y2] - [x1, y1] 是向量。你用括号,我用括号。 30 * unitVector 是一个向量。 [x1, y1] + 30 * unitVector 也是一个向量。

标签: javascript


【解决方案1】:

作为数学伪代码的算法:

  1. 计算方向:direction = (x2, y2) - (x1, y1)
  2. 计算该方向的单位向量:unitVector = direction / |direction|
  3. 将方向步骤添加到旧位置:newPos = (x1, y1) + steps * unitVector

在您的示例中,您得到:

  1. (300, 300)
  2. (0.707..., 0.707...)
  3. 30 * (0.707..., 0.707...) + (100, 100) = (121.213..., 121.213...)

新距离为~394 = ~424 - 30,存在舍入误差。

【讨论】:

  • 这个 unitVector = direction / |direction| 不总是 1 吗?
  • @BallonUra unit vector 的长度始终为 1。
【解决方案2】:

你可以像这样Partitioning a Segment in a Given Ratio:

const [x1, y1] = [100, 100];
const [x2, y2] = [400, 400];
const distance = Math.hypot(x2 - x1, y2 - y1);
const delta = 30;
const coef = delta / distance;

const calc = (p1, p2) => coef * (p2 - p1) + p1;

const x3 = calc(x1, x2);
const y3 = calc(y1, y2);

console.log(x3, y3);

【讨论】:

  • What comment should I add to code-only answers? 请不要用纯代码回答初学者的问题。
  • 为什么const calc = (p1, p2) => coef * (p2 - p1) + p1你在最后加上p1? p2呢?
  • 是的,我可能应该添加一些信息,更新
  • @Thomas Sablik 我试过但没有在这个网站上找到“初学者”的定义,而且我有点困惑,因为我不明白,OP 是不是“6 年以来的会员” , 2 个月”比我只有“7 个月”的初学者,还是“6 年”的初学者更少?或者这个术语还有其他资格吗?你能解释一下吗?
  • 初学者是指不了解某个主题的基础知识的人,例如几何学。 dictionary “已经开始教学或正在学习基础知识的人” 计算方向和单位向量通常在每门几何课程的最开始教授。请将解释发布到您的答案中。链接可能会失效。
猜你喜欢
  • 1970-01-01
  • 2010-10-30
  • 2011-04-23
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多