/// <summary> /// Use the parent field of the search nodes to trace /// a path from the end node to the start node. /// </summary> private List<Vector2> FindFinalPath(SearchNode startNode, SearchNode endNode) { closedList.Add(endNode); SearchNode parentTile = endNode.Parent; // Trace back through the nodes using the parent fields // to find the best path. while (parentTile != startNode) { closedList.Add(parentTile); parentTile = parentTile.Parent; } List<Vector2> finalPath = new List<Vector2>(); // Reverse the path and transform into world space. for (int i = closedList.Count - 1; i >= 0; i--) { finalPath.Add(new Vector2(closedList[i].Position.X * 32, closedList[i].Position.Y * 32)); } return finalPath; }
/// <summary> /// Splits our level up into a grid of nodes. /// </summary> public void InitializeSearchNodes() { searchNodes = new SearchNode[levelWidth, levelHeight]; // For each of the tiles in our map, we // will create a search node for it. for (int x = 0; x < levelWidth; x++) { for (int y = 0; y < levelHeight; y++) { // Create a search node to represent this tile. SearchNode node = new SearchNode(); node.Position = new Point(x, y); // Our enemies can only walk on grass tiles. node.Walkable = map.GetIndex(y, x) == 0; //TODOne negate: now 1 means walkable; TODOne NO! IT'S LIKE ORIGINALLY THOUGH! walk-flag // We only want to store nodes // that can be walked on. if (node.Walkable == true) { node.Neighbors = new SearchNode[4]; searchNodes[x, y] = node; } // FLAG else { // todone no Neighbor-nodes needed depending on FindPath method. oh yes they are-downside of algo implementation node.Neighbors = new SearchNode[4]; searchNodes[x, y] = node; } } } // Now for each of the search nodes, we will // connect it to each of its neighbours. for (int x = 0; x < levelWidth; x++) { for (int y = 0; y < levelHeight; y++) { SearchNode node = searchNodes[x, y]; // We only want to look at the nodes that // our enemies can walk on. if (node == null || node.Walkable == false) { continue; } // An array of all of the possible neighbors this // node could have. (We will ignore diagonals for now.) 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 }; // We loop through each of the possible neighbors for (int i = 0; i < neighbors.Length; i++) { Point position = neighbors[i]; // We need to make sure this neighbour is part of the level. if (position.X < 0 || position.X > levelWidth - 1 || position.Y < 0 || position.Y > levelHeight - 1) { continue; } SearchNode neighbor = searchNodes[position.X, position.Y]; // We will only bother keeping a reference // to the nodes that can be walked on. if (neighbor == null || neighbor.Walkable == false) { continue; } // Store a reference to the neighbor. node.Neighbors[i] = neighbor; } } } }