getNeighbors method

dynamic getNeighbors(
  1. dynamic node,
  2. dynamic allowDiagonal, [
  3. dynamic dontCrossCorners = false
])

Get the neighbors of the given node.

offsets      diagonalOffsets:

+---+---+---+ +---+---+---+ | | 0 | | | 0 | | 1 | +---+---+---+ +---+---+---+ | 3 | | 1 | | | | | +---+---+---+ +---+---+---+ | | 2 | | | 3 | | 2 | +---+---+---+ +---+---+---+

When allowDiagonal is true, if offsetsi is valid, then diagonalOffsetsi and diagonalOffsets(i + 1) % 4 is valid. @param {Node} node @param {boolean} allowDiagonal @param {boolean} dontCrossCorners

Implementation

getNeighbors(node, allowDiagonal, [dontCrossCorners = false]) {
  var x = node.x,
      y = node.y,
      neighbors = [],
      s0 = false, d0 = false,
      s1 = false, d1 = false,
      s2 = false, d2 = false,
      s3 = false, d3 = false,
      nodes = this.nodes;

  // ↑
  if (this.isWalkableAt(x, y - 1)) {
    neighbors.add(nodes[y - 1][x]);
    s0 = true;
  }
  // →
  if (this.isWalkableAt(x + 1, y)) {
    neighbors.add(nodes[y][x + 1]);
    s1 = true;
  }
  // ↓
  if (this.isWalkableAt(x, y + 1)) {
    neighbors.add(nodes[y + 1][x]);
    s2 = true;
  }
  // ←
  if (this.isWalkableAt(x - 1, y)) {
    neighbors.add(nodes[y][x - 1]);
    s3 = true;
  }

  if (!allowDiagonal) {
    return neighbors;
  }

  if (dontCrossCorners) {
    d0 = s3 && s0;
    d1 = s0 && s1;
    d2 = s1 && s2;
    d3 = s2 && s3;
  } else {
    d0 = s3 || s0;
    d1 = s0 || s1;
    d2 = s1 || s2;
    d3 = s2 || s3;
  }

  // ↖
  if (d0 && this.isWalkableAt(x - 1, y - 1)) {
    neighbors.add(nodes[y - 1][x - 1]);
  }
  // ↗
  if (d1 && this.isWalkableAt(x + 1, y - 1)) {
    neighbors.add(nodes[y - 1][x + 1]);
  }
  // ↘
  if (d2 && this.isWalkableAt(x + 1, y + 1)) {
    neighbors.add(nodes[y + 1][x + 1]);
  }
  // ↙
  if (d3 && this.isWalkableAt(x - 1, y + 1)) {
    neighbors.add(nodes[y + 1][x - 1]);
  }

  return neighbors;
}