@@ -36,6 +36,8 @@ public Position[] FindPath(Position start, Position end)
36
36
{
37
37
var nodesVisited = 0 ;
38
38
IModelAGraph < PathFinderNode > graph = new PathFinderGraph ( _world . Height , _world . Width , _options . UseDiagonals ) ;
39
+ var lowestNode = start ;
40
+ var lowestNodeDist = int . MaxValue ;
39
41
40
42
var startNode = new PathFinderNode ( position : start , g : 0 , h : 2 , parentNodePosition : start ) ;
41
43
graph . OpenNode ( startNode ) ;
@@ -62,6 +64,13 @@ public Position[] FindPath(Position start, Position end)
62
64
}
63
65
64
66
var newG = q . G + DistanceBetweenNodes ;
67
+ var distanceBetweenSuccessorAndEnd = this . CalculateDistance ( q . Position , end ) ;
68
+
69
+ if ( distanceBetweenSuccessorAndEnd < lowestNodeDist )
70
+ {
71
+ lowestNode = q . Position ;
72
+ lowestNodeDist = distanceBetweenSuccessorAndEnd ;
73
+ }
65
74
66
75
if ( _options . PunishChangeDirection )
67
76
{
@@ -72,7 +81,7 @@ public Position[] FindPath(Position start, Position end)
72
81
{
73
82
if ( qIsHorizontallyAdjacent )
74
83
{
75
- newG += Math . Abs ( successor . Position . Row - end . Row ) + Math . Abs ( successor . Position . Column - end . Column ) ;
84
+ newG += this . CalculateDistance ( successor . Position , end ) ;
76
85
}
77
86
}
78
87
@@ -81,7 +90,7 @@ public Position[] FindPath(Position start, Position end)
81
90
{
82
91
if ( ! qIsHorizontallyAdjacent )
83
92
{
84
- newG += Math . Abs ( successor . Position . Row - end . Row ) + Math . Abs ( successor . Position . Column - end . Column ) ;
93
+ newG += this . CalculateDistance ( successor . Position , end ) ;
85
94
}
86
95
}
87
96
}
@@ -101,9 +110,19 @@ public Position[] FindPath(Position start, Position end)
101
110
nodesVisited ++ ;
102
111
}
103
112
113
+ if ( _options . ClosestNodeWhenCantReach && lowestNode != start )
114
+ {
115
+ return this . FindPath ( start , lowestNode ) ;
116
+ }
117
+
104
118
return new Position [ 0 ] ;
105
119
}
106
120
121
+ private int CalculateDistance ( Position currentNode , Position endNode )
122
+ {
123
+ return Math . Abs ( currentNode . Row - endNode . Row ) + Math . Abs ( currentNode . Column - endNode . Column ) ;
124
+ }
125
+
107
126
private bool BetterPathToSuccessorFound ( PathFinderNode updateSuccessor , PathFinderNode currentSuccessor )
108
127
{
109
128
return ! currentSuccessor . HasBeenVisited ||
0 commit comments