Skip to content

Commit cf142bf

Browse files
author
Daniel Steinborn
committed
added diagonal cost
1 parent da40824 commit cf142bf

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

astar.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ var astar = {
2323
return node.f;
2424
});
2525
},
26-
search: function(grid, start, end, diagonal, heuristic) {
26+
search: function(grid, start, end, diagonal, heuristic, costDiagonal, costStraight) {
27+
costDiagonal = costDiagonal || 1;
28+
costStraight = costStraight || 1;
2729
astar.init(grid);
2830
heuristic = heuristic || astar.manhattan;
2931
diagonal = !!diagonal;
@@ -72,7 +74,7 @@ var astar = {
7274
// Found an optimal (so far) path to this node. Take score for node to see how good it is.
7375
neighbor.visited = true;
7476
neighbor.parent = currentNode;
75-
neighbor.h = neighbor.h || heuristic(neighbor.pos, end.pos);
77+
neighbor.h = neighbor.h || heuristic(neighbor.pos, end.pos, costStraight, costDiagonal);
7678
neighbor.g = gScore;
7779
neighbor.f = neighbor.g + neighbor.h;
7880

@@ -98,6 +100,11 @@ var astar = {
98100
var d2 = Math.abs (pos1.y - pos0.y);
99101
return d1 + d2;
100102
},
103+
diagonal: function(pos0, pos1, D, D2) {
104+
var d1 = Math.abs (pos1.x - pos0.x);
105+
var d2 = Math.abs (pos1.y - pos0.y);
106+
return (D * (d1 + d2)) + ((D2 - (2 * D)) * Math.min(d1, d2));
107+
},
101108
neighbors: function(grid, node, diagonals) {
102109
var ret = [];
103110
var x = node.x;

0 commit comments

Comments
 (0)