public void FindPath() { WasMoved = true; _findCount++; if (CurrentPath != null) { _pathIndex = 1; CurrentPath.Clear(); } Vector2 cellPos = SnapToHexNode(); transform.position = cellPos; Destination = cellPos; HexagonNode node = new HexagonNode(cellPos.x, cellPos.y); ShortestPathToZero startPath = new ShortestPathToZero(node, HexagonMapGenerator.Instance.MoveCost, node.Magnitude, null); _closeList.AddRange(HexagonMapGenerator.Instance.GetObstaclesByAdjacentNode(cellPos)); _closeList.Add(cellPos); CurrentPath = HexagonMapGenerator.Instance.FindPath(startPath, _openList, _closeList); _closeList.Clear(); _openList.Clear(); if (CurrentPath.Count > 1) { Destination = CurrentPath[_pathIndex]; } }
public List <Vector2> FindPath( ShortestPathToZero currentPos, List <ShortestPathToZero> openList, List <Vector2> closeList) { List <Vector2> result = new List <Vector2>(); FindPathRecursive(result, currentPos, openList, closeList); return(result); }
private void FindPathRecursive( List <Vector2> resultPath, ShortestPathToZero currentPos, List <ShortestPathToZero> openList, List <Vector2> closeList) { resultPath.Add(currentPos.GetPosition()); if (currentPos.IsDestination() || resultPath.Count >= _limitPathCount) { return; } bool isReachDestination = false; Vector2[] adjacentNodes = currentPos.Node.GetAdjacentNodes(CellSize, MapSize); for (int i = 0; i < adjacentNodes.Length; i++) { HexagonNode node = new HexagonNode(adjacentNodes[i].x, adjacentNodes[i].y); var estimatePath = new ShortestPathToZero( node, currentPos.MoveCost + MoveCost, (node - HexagonNode.zero).Magnitude, currentPos); if (closeList.Contains(adjacentNodes[i])) { continue; } if (estimatePath.IsDestination()) { //resultPath.Add(estimatePath.GetPosition()); isReachDestination = true; break; } int findedIndex = openList.IndexOf(estimatePath); if (findedIndex > -1 && openList[findedIndex].TotalCost != estimatePath.TotalCost) { openList[findedIndex] = estimatePath; } else { openList.Add(estimatePath); } } if (isReachDestination || openList.Count == 0) { return; } openList.Sort(); ShortestPathToZero currentShortPath = openList[0]; openList.RemoveAt(0); closeList.Add(currentShortPath.GetPosition()); FindPathRecursive(resultPath, currentShortPath, openList, closeList); }