javascript - 周围最近的坐标

标签 javascript algorithm path-finding

我有英雄坐标、目标坐标和范围。

假设我的英雄位于 x: 1, y: 1;

目标坐标为:x: 4, y: 4;

我正在获取范围内目标的每个坐标。因此,如果范围为 1,那么我将创建如下所示的对象数组:

[
    {x: 3, y: 3},
    {x: 4, y: 3},
    {x: 5, y: 3},
    {x: 3, y: 4},
    {x: 5, y: 4},
    {x: 3, y: 5},
    {x: 4, y: 5},
    {x: 5, y: 5}
]

仅 1 平方米 - 目标周围 8 个坐标。我用简单的算法得到了这个

const hero = {x: 1, y: 1};
const closest = {x: 4, y: 4};
const range = 1;
const coordsAround = [];


for (let i = 0; i <= range * 2; i++) {
  for (let j = 0; j <= range * 2; j++) {
    let newCoord = { x: closest.x - range + j, y: closest.y - range + i };
    //here note
    if(!((newCoord.x === 3 && newCoord.y === 3) || (newCoord.x === 4 && newCoord.y === 3))) {
      coordsAround.push(newCoord);  
    }
  }
}

此外,在推送到 coordsAround 之前,我正在执行一些检查碰撞的函数。在示例中,我只是添加了 if 语句来稍微简化一下。通过这个 if,我排除了 3,34,3

现在我的仪表板是这样的:

enter image description here

(我不小心制作了这个仪表板,所以它是 y,x 模式而不是 x,y srr)

其中粉色是英雄(1,1),红色是碰撞,金色是目标(4,4),绿色是目标周围(从上面的代码片段获得)

现在,如果没有红色瓷砖(碰撞),就可以很简单地判断哪个绿色最接近:

const realClosest = {
  x: hero.x > closest.x
    ? closest.x + 1
    : closest.x - 1,
  y: hero.y > closest.y
    ? closest.y + 1
    : closest.y - 1
};

console.log('real closest is:', realClosest, 'but it is not within coordsAournd:', coordsAround, 
           'so next closest coord is 3,4 or 4,3 but 3,4 is not within coordsAournd as well' +
            'so closest coord is 4,3');

但就我所拥有的红色瓷砖而言,我不知道如何辨别哪个是第二好,第三好等等......

最佳答案

使用自定义函数对图 block 进行排序,以便 coordsAround[0]是距离英雄最近的图 block ,coordsAround[coordsAround.length - 1]是最远的图 block :

function dist2(a, b) {
    let dx = a.x - b.x;
    let dy = a.y - b.y;

    return dx*dx + dy*dy;
}

coordsAround.sort(function (a, b) {
    let da = dist2(a, hero);
    let db = dist2(b, hero);

    if (da < db) return -1;
    if (da > db) return 1;
    return 0;
})

辅助功能dist2计算距离的平方。排序顺序将是相同的,因为 sqrt(x) < sqrt(y)x < y (并且两个值都是非负的)。鉴于您的范围是正方形,而不是圆形,您也可以使用 dist = Math.max(Math.abs(dx), Math.abs(dy)) .

关于javascript - 周围最近的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58901852/

相关文章:

javascript - 确保在重新渲染组件时执行 componentDidMount 中的代码

javascript - 提交确认

javascript - 如何重定向到 crossrider 中的书签 URL?

algorithm - 使用 ISRES 搜索算法通过 nloptr 指定约束

algorithm - 顶点和边之间的差异 [图形、算法和 DS]

javascript - 获取数据之前的渲染组件已经完成

php连接数组的两个元素

algorithm - 寻路 : Jump Point Search - Straight Moves vs Diagonal Moves

algorithm - 寻路任务——我怎样才能比 O ( n ) 更快地找到从 A 到 B 的最短路径上的下一个顶点?

c++ - 一群士兵一起在网格 map 上移动