From 29d97c2a5fd5b6ea65faead393a22a666d7ce0f4 Mon Sep 17 00:00:00 2001 From: ballparts Date: Mon, 23 Mar 2015 19:40:06 -0700 Subject: [PATCH] Allow options for diagonal pathfinding Add option to disallow pathfinding between walls diagonally. --- astar.js | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/astar.js b/astar.js index 3c617c7..22c8853 100644 --- a/astar.js +++ b/astar.js @@ -159,6 +159,8 @@ function Graph(gridIn, options) { options = options || {}; this.nodes = []; this.diagonal = !!options.diagonal; + this.diagonalIfAtMostOne = !!options.diagonalIfAtMostOne; + this.diagonalOnlyWhenNoObstacles = !!options.diagonalOnlyWhenNoObstacles; this.grid = []; for (var x = 0; x < gridIn.length; x++) { this.grid[x] = []; @@ -238,6 +240,50 @@ Graph.prototype.neighbors = function(node) { } } + if (this.diagonalIfAtMostOne) { + // Southwest + if(grid[x-1] && grid[x-1][y-1] && (grid[x-1][y].weight || grid[x][y-1].weight)) { + ret.push(grid[x-1][y-1]); + } + + // Southeast + if(grid[x+1] && grid[x+1][y-1] && (grid[x+1][y].weight || grid[x][y-1].weight)) { + ret.push(grid[x+1][y-1]); + } + + // Northwest + if(grid[x-1] && grid[x-1][y+1] && (grid[x-1][y].weight || grid[x][y+1].weight)) { + ret.push(grid[x-1][y+1]); + } + + // Northeast + if(grid[x+1] && grid[x+1][y+1] && (grid[x+1][y].weight || grid[x][y+1].weight)) { + ret.push(grid[x+1][y+1]); + } + } + + if(this.diagonalOnlyWhenNoObstacles) { + // Southwest + if(grid[x-1] && grid[x-1][y-1] && grid[x-1][y].weight && grid[x][y-1].weight) { + ret.push(grid[x-1][y-1]); + } + + // Southeast + if(grid[x+1] && grid[x+1][y-1] && grid[x+1][y].weight && grid[x][y-1].weight) { + ret.push(grid[x+1][y-1]); + } + + // Northwest + if(grid[x-1] && grid[x-1][y+1] && grid[x-1][y].weight && grid[x][y+1].weight) { + ret.push(grid[x-1][y+1]); + } + + // Northeast + if(grid[x+1] && grid[x+1][y+1] && grid[x+1][y].weight && grid[x][y+1].weight) { + ret.push(grid[x+1][y+1]); + } + } + return ret; }; @@ -404,4 +450,4 @@ return { Graph: Graph }; -}); +}); \ No newline at end of file