private void InitializeSearchNodes(Map map) { searchNodes = new SearchNode[levelWidth, levelHeight]; //Create a search node for each tile for (int x = 0; x < levelWidth; x++) { for (int y = 0; y < levelHeight; y++) { //create search node for this tile SearchNode node = new SearchNode(); node.Position = new Point(x, y); //check if tile is walkable or not node.Walkable = map.GetIndex(x, y) == 0 || map.GetIndex(x,y) == 4; //if walkable then store the node if (node.Walkable == true) { node.Neighbors = new SearchNode[4]; searchNodes[x, y] = node; } } } //connect search node to neighbor nodes for (int x = 0; x < levelWidth; x++) { for (int y = 0; y < levelHeight; y++) { SearchNode node = searchNodes[x, y]; //check if node is walkable if (node == null || node.Walkable == false) { continue; } //array of all the neighbors this node has Point[] neighbors = new Point[] { new Point (x, y - 1), // The node above the current node new Point (x, y + 1), // The node below the current node. new Point (x - 1, y), // The node left of the current node. new Point (x + 1, y), // The node right of the current node }; for (int i = 0; i < neighbors.Length; i++) { Point position = neighbors[i]; if (position.X < 0 || position.X > levelWidth - 1 || position.Y < 0 || position.Y > levelHeight - 1) { continue; } SearchNode neighbor = searchNodes[position.X, position.Y]; if (neighbor == null || neighbor.Walkable == false) { continue; } node.Neighbors[i] = neighbor; } } } }
private List<Vector2> FindFinalPath(SearchNode startNode, SearchNode endNode) { closedList.Add(endNode); SearchNode parentTile = endNode.Parent; while (parentTile != startNode) { closedList.Add(parentTile); parentTile = parentTile.Parent; } List<Vector2> finalPath = new List<Vector2>(); for (int i = closedList.Count - 1; i >= 0; i--) { finalPath.Add(new Vector2(closedList[i].Position.X * 50, closedList[i].Position.Y * 50)); } return finalPath; }