private void InitializeSearchNodes(Level level) { searchNodes = new SearchNode[Width * Height]; for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { SearchNode node = new SearchNode(); node.Position = new Point(x, y); node.Walkable = !level.GetTile(x, y).IsSolid(); if (node.Walkable) { node.Neighbors = new SearchNode[4]; searchNodes[x + y * Width] = node; } } } for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { SearchNode node = searchNodes[x + y * Width]; if (node == null || node.Walkable == false) { continue; } Point[] neighbors = new Point[] { new Point(x, y - 1), new Point(x, y + 1), new Point(x - 1, y), new Point(x + 1, y) }; for (int i = 0; i < neighbors.Length; i++) { Point position = neighbors[i]; if (position.X < 0 || position.X >= Width || position.Y < 0 || position.Y >= Height) { continue; } SearchNode neighbor = searchNodes[position.X + position.Y * Width]; 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 * Tile.Size, closedList[i].Position.Y * Tile.Size)); } return finalPath; }