IEnumerator showPath(IList <AStarNode> list, AStarMap map) { if (list == null || list.Count == 0) { yield return(new WaitForSeconds(0.1f)); print("No Path"); } else { var obj = GameObject.Instantiate(m_Rect); obj.SetActive(true); obj.transform.SetParent(transform); obj.transform.localScale = Vector3.one; var img = obj.GetComponent <SpriteRenderer>(); img.color = Color.red; foreach (var i in list) { yield return(new WaitForSeconds(0.1f)); img.transform.localPosition = map.GetMapData().GetMapPoints()[i.X, i.Y].Position;//new Vector2(10*i.X,10*i.Y); } } }
public static void run(String[] args) { Point a = new Point(49, 49); Point b = new Point(0, 0); Logger log = new Logger(); Stopwatch s = new Stopwatch(); log.addToLog("Initializing " + mapWidth + "x" + mapHeight + " map..."); initMap(); AStarMap map = new AStarMap(mapWidth, mapHeight, obstacleMap); log.addToLog("Generating Bresenham's Line from " + a.x + "," + a.y + " to " + b.x + "," + b.y + "..."); s.Start(); List <Point> line = Bresenham.getCellsOnLine(a, b); s.Stop(); log.addToLog("Generation took " + s.ElapsedMilliseconds + " ms"); String str = ""; foreach (Point point in line) { str = str + "(" + point.x + "," + point.y + ") "; } log.addToLog("Line is:" + str); log.addToLog("Writing line to map..."); log.addToLog("Printing map..."); new PrintMap(map, line); }
public void Init(int row, int col, MapCtr map, AStarMap astarMap, PlayerCtrEx target, bool isLeft) { startRow = row; startCol = col; m_data = GetComponent <PlayerData> (); m_data.Init(row, col, map); m_astarMap = astarMap; m_target = target; m_data.RegisterMoveOverEvent(AutoMoveOver); if (isLeft) { if (m_astarMap.GetCell(m_data.Row, m_data.Column).IsToLeft) { m_data.Move(-1, 0); } else { m_data.Move(1, 0); } } else { if (m_astarMap.GetCell(m_data.Row, m_data.Column).IsToRight) { m_data.Move(1, 0); } else { m_data.Move(-1, 0); } } }
/** * removes the specified node from the open list * @param the node to remove from the open list */ public void RemoveFromOpenList(short nodeId, AStarMap map) { AStarNode removeNode = FindInOpenList(nodeId); if (removeNode != null) { AStarNode next = removeNode.Next; AStarNode previous = removeNode.Previous; if (next != null) { next.Previous = previous; } if (previous != null) { previous.Next = next; } if (headOfOpenList == removeNode) { headOfOpenList = next; } removeNode.Next = null; removeNode.Previous = null; removeNode.Flag = AStarNode.E_AStarFlags.Unchecked; map.SetAStarFlags(removeNode.NodeID, AStarNode.E_AStarFlags.Unchecked); openSize--; } }
public static void run(String[] args) { Point a = new Point(49, 49); Point b = new Point(0, 0); Logger log = new Logger(); Stopwatch s = new Stopwatch(); log.addToLog("Initializing "+mapWidth+"x"+mapHeight+" map..."); initMap(); AStarMap map = new AStarMap(mapWidth, mapHeight, obstacleMap); log.addToLog("Generating Bresenham's Line from "+a.x+","+a.y+" to "+b.x+","+b.y+"..."); s.Start(); List<Point> line = Bresenham.getCellsOnLine(a, b); s.Stop(); log.addToLog("Generation took " + s.ElapsedMilliseconds + " ms"); String str = ""; foreach(Point point in line) { str = str+"("+point.x+","+point.y+") "; } log.addToLog("Line is:" + str); log.addToLog("Writing line to map..."); log.addToLog("Printing map..."); new PrintMap(map, line); }
public AStarReturnObject(AStarNode finalNode, ArrayList closedList, BinaryHeap heap, AStarMap map) { this.finalNode = finalNode; this.closedList = closedList; this.heap = heap; this.map = map; }
public static void run(String[] args) { Logger log = new Logger(); Stopwatch s = new Stopwatch(); log.addToLog("Map initializing..."); AStarMap map = new AStarMap(mapData.getMapWidth(), mapData.getMapHeight(), mapData.getObstacleMap()); log.addToLog("Heuristic initializing..."); //AStarHeuristic heuristic = new ClosestHeuristic(); AStarHeuristic heuristic = new DiagonalHeuristic(); log.addToLog("AStar initializing..."); AStar aStar = new AStar(map, heuristic); log.addToLog("Calculating shortest path..."); s.Start(); List<Point> shortestPath = aStar.calcShortestPath(startX, startY, goalX, goalY); s.Stop(); log.addToLog("Time to calculate path in milliseconds: " + s.ElapsedMilliseconds); log.addToLog("Printing map of shortest path..."); new PrintMap(map, shortestPath); }
void SetCharWaypoint(Vector3 position) { if (selectedChar.path.waypoints.Count < 1) { startNode = FindClosestNode(selectedChar.position); } else { startNode = FindClosestNode(selectedChar.path.waypoints[selectedChar.path.waypoints.Count - 1].position); } goalNode = FindClosestNode(position); if (goalNode != null && startNode != null && startNode != goalNode) { AStarMap astar = new AStarMap(nodeList, goalNode, startNode); Path newPath = astar.AStarPath(); newPath.OptimizePath(); selectedChar.AddWaypoints(newPath.waypoints); selectedChar.path.CreatePathMesh(); PurgeAllNodes(); } else { Debug.Log("start and goal node is probably the same"); } startNode = null; goalNode = null; }
void ReadCatch() { AStarMap map = AStarMapStream.Read(Application.dataPath + "/MapCatch"); FromMap(map); FileUtil.DeleteFileOrDirectory(Application.dataPath + "/MapCatch"); }
public static void run(String[] args) { Logger log = new Logger(); Stopwatch s = new Stopwatch(); log.addToLog("Map initializing..."); AStarMap map = new AStarMap(mapData.getMapWidth(), mapData.getMapHeight(), mapData.getObstacleMap()); log.addToLog("Heuristic initializing..."); //AStarHeuristic heuristic = new ClosestHeuristic(); AStarHeuristic heuristic = new DiagonalHeuristic(); log.addToLog("AStar initializing..."); AStar aStar = new AStar(map, heuristic); log.addToLog("Calculating shortest path..."); s.Start(); List <Point> shortestPath = aStar.calcShortestPath(startX, startY, goalX, goalY); s.Stop(); log.addToLog("Time to calculate path in milliseconds: " + s.ElapsedMilliseconds); log.addToLog("Printing map of shortest path..."); new PrintMap(map, shortestPath); }
/// <summary> /// Start is called on the frame when a script is enabled just before /// any of the Update methods is called the first time. /// </summary> void Start() { // AStarPoint[,] array = new AStarPoint[128,64]; AStarPoint[,] array = new AStarPoint[128, 64]; for (int i = 0; i < array.GetLength(0); ++i) { for (int j = 0; j < array.GetLength(1); ++j) { var obj = GameObject.Instantiate(m_Rect); obj.SetActive(true); obj.transform.SetParent(transform); obj.transform.localScale = Vector3.one; obj.transform.localPosition = new Vector2(i * 0.2f, j * 0.2f); var img = obj.GetComponent <SpriteRenderer>(); array[i, j] = new AStarPoint(i, j); array[i, j].Value = m_Txt.GetPixel(i, j) == Color.white?0:1; array[i, j].Position = obj.transform.localPosition; img.color = array[i, j].Value == 0?Color.white:Color.black; obj.GetComponent <CirclePointSprite>().OnMouseUpHandler = OnMouseClickHandler; } } map = new AStarMap(new AStarMapData(array)); // AStar.GetInstance().FindPathAsyn(map,new AStarNode(10,10),new AStarNode(115,32),true,(e)=> // { // print("1cost time "+(Time.time-t)); // StartCoroutine(showPath(e,map)); // }); // AStar.GetInstance().FindPathAsyn(map.Clone(),new AStarNode(11,9),new AStarNode(115,8),true,(e)=> // { // print("2cost time "+(Time.time-t)); // StartCoroutine(showPath(e,map)); // }); // AStar.GetInstance().FindPathAsyn(map.Clone(),new AStarNode(17,23),new AStarNode(66,8),true,(e)=> // { // print("3cost time "+(Time.time-t)); // StartCoroutine(showPath(e,map)); // }); // AStar.GetInstance().FindPathAsyn(map.Clone(),new AStarNode(66,7),new AStarNode(15,22),true,(e)=> // { // print("4cost time "+(Time.time-t)); // StartCoroutine(showPath(e,map)); // }); // AStar.GetInstance().FindPathAsyn(map.Clone(),new AStarNode(115,31),new AStarNode(11,11),true,(e)=> // { // print("5cost time "+(Time.time-t)); // StartCoroutine(showPath(e,map)); // }); }
/// <summary> /// Start is called on the frame when a script is enabled just before /// any of the Update methods is called the first time. /// </summary> void Start() { AStarPoint[,] array = new AStarPoint[(int)128, (int)64]; for (int i = 0; i < array.GetLength(0); ++i) { for (int j = 0; j < array.GetLength(1); ++j) { var obj = GameObject.Instantiate(m_Rect); obj.SetActive(true); obj.transform.SetParent(transform); obj.transform.localScale = Vector3.one; obj.GetComponent <RectTransform>().anchoredPosition = new Vector2(i * 10, j * 10); var img = obj.GetComponent <Image>(); array[i, j] = new AStarPoint(i, j); array[i, j].Value = m_Txt.GetPixel(i, j) == Color.white?0:1; array[i, j].Position = obj.GetComponent <RectTransform>().anchoredPosition; img.color = array[i, j].Value == 0?Color.white:Color.black; } } AStarMap map = new AStarMap(new AStarMapData(array)); float t = Time.time; //var rst = map.GetPath(new AStarNode(1,1),new AStarNode(6,10),false); AStar.GetInstance().FindPathAsyn(map, new AStarNode(10, 10), new AStarNode(115, 32), true, (e) => { print("1cost time " + (Time.time - t)); StartCoroutine(showPath(e, map)); }); AStar.GetInstance().FindPathAsyn(map.Clone(), new AStarNode(11, 9), new AStarNode(115, 8), true, (e) => { print("2cost time " + (Time.time - t)); StartCoroutine(showPath(e, map)); }); AStar.GetInstance().FindPathAsyn(map.Clone(), new AStarNode(17, 23), new AStarNode(66, 8), true, (e) => { print("3cost time " + (Time.time - t)); StartCoroutine(showPath(e, map)); }); AStar.GetInstance().FindPathAsyn(map.Clone(), new AStarNode(66, 7), new AStarNode(15, 22), true, (e) => { print("4cost time " + (Time.time - t)); StartCoroutine(showPath(e, map)); }); AStar.GetInstance().FindPathAsyn(map.Clone(), new AStarNode(115, 31), new AStarNode(11, 11), true, (e) => { print("5cost time " + (Time.time - t)); StartCoroutine(showPath(e, map)); }); }
/** * Initialise the A Star machine to run a search * @param the Goal we are searching towards * @param the Storage which will store the open and closed lists * @param the map which will get the neighbours, heuristic/action costs for the search */ public void Setup(AStarGoal _goal, AStarStorage _storage, AStarMap _aStarMap) { Goal = _goal; Storage = _storage; Map = _aStarMap; Storage.ResetStorage(Map); }
public PrintMap(AStarMap map, List <Point> shortestPath) { StringBuilder sb = new StringBuilder(); AStarCell cell; for (int y = 0; y < map.getMapHeight(); y++) { if (y == 0) { for (int i = 0; i <= map.getMapHeight(); i++) { sb.Append("-"); } sb.AppendLine(); } sb.Append("|"); for (int x = 0; x < map.getMapWith(); x++) { cell = map.getCell(x, y); if (cell == null || cell.isObstacle()) { sb.Append("X"); } else if (isStart(shortestPath, cell.getPoint())) { sb.Append("s"); } else if (isGoal(shortestPath, cell.getPoint())) { sb.Append("g"); } else if (contains(shortestPath, cell.getPoint())) { sb.Append("?"); } else { sb.Append(" "); } if (y == map.getMapHeight()) { sb.Append("_"); } } sb.Append("|"); sb.AppendLine(); } for (int i = 0; i <= map.getMapHeight(); i++) { sb.Append("-"); } System.Console.SetWindowSize(System.Console.LargestWindowWidth, System.Console.LargestWindowHeight); System.Console.Write(sb.ToString()); }
public PrintMap(AStarMap map, List<Point> shortestPath) { StringBuilder sb = new StringBuilder(); AStarCell cell; for(int y = 0; y < map.getMapHeight(); y++) { if(y == 0) { for (int i = 0; i <= map.getMapHeight(); i++) { sb.Append("-"); } sb.AppendLine(); } sb.Append("|"); for(int x = 0; x < map.getMapWith(); x++) { cell = map.getCell(x, y); if(cell == null || cell.isObstacle()) { sb.Append("X"); } else if(isStart(shortestPath, cell.getPoint())) { sb.Append("s"); } else if(isGoal(shortestPath, cell.getPoint())) { sb.Append("g"); } else if (contains(shortestPath, cell.getPoint())) { sb.Append("?"); } else { sb.Append(" "); } if(y==map.getMapHeight()) { sb.Append("_"); } } sb.Append("|"); sb.AppendLine(); } for (int i = 0; i <= map.getMapHeight(); i++) { sb.Append("-"); } System.Console.SetWindowSize(System.Console.LargestWindowWidth, System.Console.LargestWindowHeight); System.Console.Write(sb.ToString()); }
/** * Cleanup */ public void Cleanup() { Goal = null; Map = null; Storage = null; CurrentNode = null; Start = 0; End = 0; }
public static void Write(AStarMap map, string path) { FileStream fs = new FileStream(path, FileMode.Create); string jsonStr = JsonMapper.ToJson(map); byte[] data = Encoding.ASCII.GetBytes(jsonStr); fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); }
// Use this for initialization public void Init(int row, int col, MapCtr map, AStarMap astarMap, PlayerCtrEx target) { startRow = row; startCol = col; m_data = GetComponent <PlayerData> (); m_data.Init(row, col, map); m_astarMap = astarMap; m_target = target; m_data.RegisterMoveOverEvent(MoveOver); FindPath(); }
AStarMap ToMap() { AStarMap map = new AStarMap(m_row, m_column); for (int i = 0; i < m_row; i++) { for (int j = 0; j < m_column; j++) { map.SetCell(i, j, m_cellArray [j, i].ToMapCell()); } } return(map); }
void FromMap(AStarMap map) { ClearMap(); m_column = map.Column; m_row = map.Row; CreateMap(); for (int i = 0; i < m_row; i++) { for (int j = 0; j < m_column; j++) { m_cellArray [j, i].FromMapCell(map.GetCell(i, j)); } } }
public static AStarMap Read(string path) { FileStream fs = new FileStream(path, FileMode.Open); byte[] data = new byte[fs.Length]; fs.Seek(0, SeekOrigin.Begin); fs.Read(data, 0, (int)fs.Length); string jsonStr = Encoding.ASCII.GetString(data); AStarMap map = JsonMapper.ToObject <AStarMap> (jsonStr); fs.Close(); return(map); }
public void ReadMap() { if (!string.IsNullOrEmpty(m_filePath)) { SaveMap(); } m_filePath = EditorUtility.OpenFilePanel("Read map file", Application.dataPath, "txt"); if (string.IsNullOrEmpty(m_filePath)) { return; } AStarMap map = AStarMapStream.Read(m_filePath); FromMap(map); }
IEnumerator showPath(IList <AStarNode> list, AStarMap map) { var obj = GameObject.Instantiate(m_Rect); obj.SetActive(true); obj.transform.SetParent(transform); obj.transform.localScale = Vector3.one; var img = obj.GetComponent <Image>(); img.color = Color.red; foreach (var i in list) { yield return(new WaitForSeconds(0.1f)); img.GetComponent <RectTransform>().anchoredPosition = map.GetMapData().GetMapPoints()[i.X, i.Y].Position;//new Vector2(10*i.X,10*i.Y); } }
public void ReadMap(string fileName) { Debug.Log("MapCtr::ReadMap"); Debug.Log(GameDebug.GetInvokeClassAndMethodName(1)); Debug.Log(GameDebug.GetInvokeClassAndMethodName(2)); Debug.Log(GameDebug.GetInvokeClassAndMethodName(3)); if (string.IsNullOrEmpty(fileName)) { return; } Debug.Log(Application.dataPath); string dir = Application.dataPath + "/"; PathfindingMap = AStarMapStream.Read(dir + fileName + "_astar.txt"); MapData map = MapStream.Read(dir + fileName + ".txt"); FromMapData(map); }
public void AutoAStarMap() { if (cells == null) { return; } string filePath; filePath = EditorUtility.SaveFilePanel("Save map file", Application.dataPath, "", "txt"); if (string.IsNullOrEmpty(filePath)) { return; } AStarMap map = SpriteMap2AStarMap.SpriteMapToAStarMap(ToMapData()); AStarMapStream.Write(map, filePath); Debug.Log("AutoAStarMap success."); }
void Start() { map = GetComponent <AStarMap>(); var trigger = GetComponent <EventTrigger>(); var entry = new EventTrigger.Entry(); entry.eventID = EventTriggerType.PointerClick; entry.callback = new EventTrigger.TriggerEvent(); entry.callback.AddListener(e => { if (map.CanChange) { float X = Input.mousePosition.x - Screen.width / 2f + 40; float Y = Input.mousePosition.y - Screen.height / 2f + 40; var pos = AStarMap.Pos2Index(new Vector2(X, Y)); map[pos.Item1, pos.Item2].Change(); } }); trigger.triggers.Add(entry); }
static void SetAStarMapCell_Second(MapData map, MapCellData cell, ref AStarMap astarMap) { // check second time CELL_TYPE curType = (CELL_TYPE)cell.cellType; if (curType == CELL_TYPE.STONE || curType == CELL_TYPE.WALL) { return; } if (cell.row - 1 >= 0) { MapCellData downCell = map.cells [(cell.row - 1) * map.column + cell.col]; CELL_TYPE downType = (CELL_TYPE)downCell.cellType; if (downType == CELL_TYPE.WALL || downType == CELL_TYPE.STONE || downType == CELL_TYPE.LADDER) { //right if (cell.col + 1 < map.column) { MapCellData rightCell = map.cells [(cell.row) * map.column + cell.col + 1]; CELL_TYPE rightType = (CELL_TYPE)rightCell.cellType; if (rightType != CELL_TYPE.WALL && rightType != CELL_TYPE.STONE) { //astarMapCell.IsToRight = true; astarMap.GetCell(rightCell.row, rightCell.col).IsToLeft = true; } } //left if (cell.col - 1 >= 0) { MapCellData leftCell = map.cells [(cell.row) * map.column + cell.col - 1]; CELL_TYPE leftType = (CELL_TYPE)leftCell.cellType; if (leftType != CELL_TYPE.WALL && leftType != CELL_TYPE.STONE) { //astarMapCell.IsToLeft = true; astarMap.GetCell(leftCell.row, leftCell.col).IsToRight = true; } } } } }
public static AStarMap SpriteMapToAStarMap(MapData map) { AStarMap astar = new AStarMap(map.row, map.column); for (int i = 0; i < map.row; i++) { for (int j = 0; j < map.column; j++) { SetAStarMapCell_First(map, map.cells [i * map.column + j], ref astar); } } for (int i = 0; i < map.row; i++) { for (int j = 0; j < map.column; j++) { SetAStarMapCell_Second(map, map.cells [i * map.column + j], ref astar); } } return(astar); }
public static void run(String[] args) { Logger log = new Logger(); Stopwatch s = new Stopwatch(); log.addToLog("Map initializing..."); AStarMap map = new AStarMap(mapData.getMapWidth(), mapData.getMapHeight(), mapData.getObstacleMap()); s.Start(); PathFinder pathfinder = new PathFinder(map); Point start = new Point(startX, startY); Point goal = new Point(goalX, goalY); List<Point> optimizedWaypoints = pathfinder.findStraightPath(start, goal); s.Stop(); log.addToLog("Total pathfinding took: " + s.ElapsedMilliseconds + " ms"); log.addToLog("Printing map of optimized path..."); new PrintMap(map, optimizedWaypoints); }
public static void run(String[] args) { Logger log = new Logger(); Stopwatch s = new Stopwatch(); log.addToLog("Map initializing..."); AStarMap map = new AStarMap(mapData.getMapWidth(), mapData.getMapHeight(), mapData.getObstacleMap()); s.Start(); PathFinder pathfinder = new PathFinder(map); Point start = new Point(startX, startY); Point goal = new Point(goalX, goalY); List <Point> optimizedWaypoints = pathfinder.findStraightPath(start, goal); s.Stop(); log.addToLog("Total pathfinding took: " + s.ElapsedMilliseconds + " ms"); log.addToLog("Printing map of optimized path..."); new PrintMap(map, optimizedWaypoints); }
static Vector2 GetVacantPoint(int xStartRW, int yStartRW, AStarMap mapHook) { //layerMask -> red + blue int layerMask = (1 << 8) | (1 << 9); Collider[] units = Physics.OverlapBox(new Vector3(xStartRW + 2.5f, yStartRW + 2.5f, 0f), new Vector3(2.5f, 2.5f, 0f), Quaternion.identity, layerMask); AStarNode[,] map = mapHook.map; for (int i = 0; i < units.Length; i++) { map[(int)(units[i].transform.position.x), (int)(units[i].transform.position.y)].walkable = false; } List <Vector2> possiblePositions = new List <Vector2>(); for (int i = xStartRW; i < xStartRW + 6; i++) { for (int j = yStartRW; j < yStartRW + 6; j++) { if (map[i, j].walkable) { possiblePositions.Add(map[i, j].pos); } } } for (int i = 0; i < units.Length; i++) { map[(int)(units[i].transform.position.x), (int)(units[i].transform.position.y)].walkable = true; } if (possiblePositions.Count == 0) { Debug.Log("All is lost"); return(new Vector2(-1f, -1f)); } Vector2 target = possiblePositions[Random.Range(0, possiblePositions.Count)]; return(target); }
/** * Adds the specified node to the open list. * Insert new node to head of closed list * @param the node to add */ public void AddToClosedList(AStarNode node, AStarMap map) { AStarNode currNode = headOfClosedList; if (currNode != null) { node.Next = currNode; node.Previous = null; currNode.Previous = node; headOfClosedList = node; map.SetAStarFlags(node.NodeID, AStarNode.E_AStarFlags.Closed); node.Flag = AStarNode.E_AStarFlags.Closed; } else { headOfClosedList = node; node.Next = null; node.Previous = null; map.SetAStarFlags(node.NodeID, AStarNode.E_AStarFlags.Closed); node.Flag = AStarNode.E_AStarFlags.Closed; } }
void SetCharWaypoint(Vector3 position) { if (startNode == null) { startNode = FindClosestNode(selectedChar.position); } Node goalNode = FindClosestNode(position); if (goalNode != null) { AStarMap astar = new AStarMap(nodeList, goalNode, startNode); astar.AStarPath(); Path path = new Path(astar.result); allPaths.Add(path); path.OptimizePath(); selectedChar.path = path; } else { if (selectedChar.path.waypoints.Count >= 1) { for (int i = 0; i < selectedChar.path.waypoints.Count - 2; i++) { Vector3 closestPoint = ClosestPointOnLine(selectedChar.path.waypoints[i].position, selectedChar.path.waypoints[i + 1].position, position); if (Vector3.Distance(closestPoint, position) < 0.5f) { Node newNode = new Node(closestPoint.x, closestPoint.z); nodeList.Add(newNode); break; } } } } startNode = null; goalNode = null; }
/** * Removes the first node from the open list * @return the node at the head of the list */ public AStarNode RemoveCheapestOpenNode(AStarMap map) { if (openSize == 0) { return(null); } AStarNode head = headOfOpenList; if (openSize == 1) { headOfOpenList.Next = null; headOfOpenList.Previous = null; headOfOpenList = null; head.Flag = AStarNode.E_AStarFlags.Unchecked; map.SetAStarFlags(head.NodeID, AStarNode.E_AStarFlags.Unchecked); openSize--; } else if (openSize > 1) { AStarNode front = headOfOpenList; AStarNode Next = headOfOpenList.Next; front.Next = null; front.Previous = null; front.Flag = AStarNode.E_AStarFlags.Unchecked; map.SetAStarFlags(front.NodeID, AStarNode.E_AStarFlags.Unchecked); headOfOpenList = Next; headOfOpenList.Previous = null; head = front; openSize--; } return(head); }
public PathFinder(AStarMap map) { this.map = map; }
void Awake() { map = GetComponent<AStarMap>(); requestManager = GetComponent<PathRequestManager>(); }