Skip to content

Commit

Permalink
ADD Dictionary to be used as quick check if tile is at open list
Browse files Browse the repository at this point in the history
  • Loading branch information
brunomikoski committed Mar 11, 2018
1 parent 220496b commit 63ef36d
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions Assets/[Pathfinding]/Scripts/Pathfinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public static class Pathfinder
private static GridController gridController;

private static List<Tile> openList = new List<Tile>();
private static Dictionary<int, Tile> tileIndexToTileObjectOpen = new Dictionary<int, Tile>();
private static HashSet<Tile> closedList = new HashSet<Tile>();

public static void Initialize( GridController targetGridController )
Expand All @@ -21,6 +22,7 @@ public static void Initialize( GridController targetGridController )
public static List<Vector2Int> GetPath( Vector2Int from, Vector2Int to )
{
openList.Clear();
tileIndexToTileObjectOpen.Clear();
closedList.Clear();

int fromIndex = gridController.TilePosToIndex( from.x, from.y );
Expand All @@ -30,11 +32,12 @@ public static List<Vector2Int> GetPath( Vector2Int from, Vector2Int to )
Tile destinationTile = gridController.Tiles[toIndex];

openList.Add( initialTile );
tileIndexToTileObjectOpen.Add( initialTile.Index, initialTile );

while ( openList.Count > 0 )
{
Tile currentTile = openList[0];
for ( int i = openList.Count - 1; i >= 1; --i )
for ( int i = 1; i < openList.Count; ++i )
{
if ( openList[i].FCost < currentTile.FCost ||
openList[i].FCost == currentTile.FCost &&
Expand All @@ -45,32 +48,35 @@ public static List<Vector2Int> GetPath( Vector2Int from, Vector2Int to )
}

openList.Remove( currentTile );
tileIndexToTileObjectOpen.Remove( currentTile.Index );
closedList.Add( currentTile );

if ( currentTile == destinationTile )
break;

Tile[] neighbours = GetPathTileNeighbors( currentTile );

for ( int i = neighbours.Length - 1; i >= 0; --i )
foreach ( Tile neighbourPathTile in neighbours )
{
Tile neighbourPathTile = neighbours[i];
if ( neighbourPathTile == null )
continue;

if ( closedList.Contains( neighbourPathTile ) )
continue;

float movementCostToNeighbour = currentTile.GCost + GetDistance( currentTile, neighbourPathTile );
bool isAtOpenList = openList.Contains( neighbourPathTile );
bool isAtOpenList = tileIndexToTileObjectOpen.ContainsKey( neighbourPathTile.Index );
if ( movementCostToNeighbour < neighbourPathTile.GCost || !isAtOpenList )
{
neighbourPathTile.SetGCost( movementCostToNeighbour );
neighbourPathTile.SetHCost( GetDistance( neighbourPathTile, destinationTile ) );
neighbourPathTile.SetParent( currentTile );

if ( !isAtOpenList )
{
openList.Add( neighbourPathTile );
tileIndexToTileObjectOpen.Add( neighbourPathTile.Index, neighbourPathTile );
}
}
}
}
Expand Down

0 comments on commit 63ef36d

Please sign in to comment.