【问题标题】:Get next XY position closest to a given target XY position获取最接近给定目标 XY 位置的下一个 XY 位置
【发布时间】:2016-03-22 16:11:15
【问题描述】:

我在屏幕上设置的 XY 位置(例如 x=100,y=200)有一个点 (A),我在屏幕上的随机 XY 位置(例如 x=50)有另一个点 (B) , y = 50)。

我想将点 B 沿直线移动到点 A。

我如何计算 B 必须移动的 XY 位置?

【问题讨论】:

    标签: javascript algorithm geometry


    【解决方案1】:

    如果需要计算 B 和 A 之间的所有整数位置,可以考虑使用Bresenham algorithm

    【讨论】:

      【解决方案2】:

      以下应该可以给出一个思路。 B点是一个随机点,x和y值在+/-100之间。

      var  A = {x:100,
                y:100},
           B = {x:Math.floor(Math.random()*201)-100,
                y:Math.floor(Math.random()*201)-100},
        diff = {x: A.x - B.x,
                y: A.y - B.y},
       steps = Math.min(diff.x, diff.y);
      for (var i = 0; i < steps; i++) {
         B.x = B.x + diff.x/steps;
         B.y = B.y + diff.y/steps;
         console.log("Step #"+i+" B moving to X: " + B.x + " Y: " + B.y);
      // plotB(Math.round(B.x), Math.round(B.y));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-08
        • 1970-01-01
        • 2015-08-06
        • 2018-08-13
        • 1970-01-01
        • 2020-04-12
        相关资源
        最近更新 更多