From 63ef36d72ef2b8b833d8b209f65e8ce607fd3889 Mon Sep 17 00:00:00 2001 From: Bruno Mikoski Date: Sun, 11 Mar 2018 18:35:38 -0300 Subject: [PATCH] ADD Dictionary to be used as quick check if tile is at open list --- Assets/[Pathfinding]/Scripts/Pathfinder.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Assets/[Pathfinding]/Scripts/Pathfinder.cs b/Assets/[Pathfinding]/Scripts/Pathfinder.cs index 9c69ac0..f630c72 100644 --- a/Assets/[Pathfinding]/Scripts/Pathfinder.cs +++ b/Assets/[Pathfinding]/Scripts/Pathfinder.cs @@ -11,6 +11,7 @@ public static class Pathfinder private static GridController gridController; private static List openList = new List(); + private static Dictionary tileIndexToTileObjectOpen = new Dictionary(); private static HashSet closedList = new HashSet(); public static void Initialize( GridController targetGridController ) @@ -21,6 +22,7 @@ public static void Initialize( GridController targetGridController ) public static List GetPath( Vector2Int from, Vector2Int to ) { openList.Clear(); + tileIndexToTileObjectOpen.Clear(); closedList.Clear(); int fromIndex = gridController.TilePosToIndex( from.x, from.y ); @@ -30,11 +32,12 @@ public static List 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 && @@ -45,6 +48,7 @@ public static List GetPath( Vector2Int from, Vector2Int to ) } openList.Remove( currentTile ); + tileIndexToTileObjectOpen.Remove( currentTile.Index ); closedList.Add( currentTile ); if ( currentTile == destinationTile ) @@ -52,9 +56,8 @@ public static List GetPath( Vector2Int from, Vector2Int to ) 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; @@ -62,7 +65,7 @@ public static List GetPath( Vector2Int from, Vector2Int to ) 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 ); @@ -70,7 +73,10 @@ public static List GetPath( Vector2Int from, Vector2Int to ) neighbourPathTile.SetParent( currentTile ); if ( !isAtOpenList ) + { openList.Add( neighbourPathTile ); + tileIndexToTileObjectOpen.Add( neighbourPathTile.Index, neighbourPathTile ); + } } } }