最近坐标

Closest coordinate around

我有英雄坐标,目标坐标和射程。

假设我的英雄在 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.

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

(我不小心做了这个仪表板所以它是 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');

但就我的红色方块而言,我不知道如何判断哪个是第二好,第三好等等..

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

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)).