public void AddNode(int x, int y, MapGridNode node) { //索引表 mapGridCoordIndexArray[x, y] = node; //原表 mapGridNodeList.Add(node); }
//请求Astar寻路 public static void RequestPathFind(MapGridNode beginNode, MapGridNode endNode, MapInfo mapInfo, AstarResult callback, Object targetObj = null) { //TODO 通过策略,决定用什么寻路方法,此处用Astar AstarPathFinder pathFinder = new AstarPathFinder(beginNode, endNode, mapInfo, callback); pathFinder.FindPath(); }
public AstarPathFinder(MapGridNode begin, MapGridNode end, MapInfo mapInfo, AstarResult callback) { findMapInfo = mapInfo; targetMapPathFindData = CreatPathFindData(mapInfo); beginNode = targetMapPathFindData[begin.coordx, begin.coordy]; endNode = targetMapPathFindData[end.coordx, end.coordy]; findResultCallback = callback; }
//根据地图数据,生成寻路信息 private AstarNode[,] CreatPathFindData(MapInfo mapInfo) { AstarNode[,] targetMapPathFindData = new AstarNode[mapInfo.mapLength, mapInfo.mapWith]; for (int i = 0; i < mapInfo.nodeCount; i++) { MapGridNode thisNode = mapInfo.GetNodeByIndex(i); targetMapPathFindData[thisNode.coordx, thisNode.coordy] = new AstarNode(thisNode.coordx, thisNode.coordy); } return(targetMapPathFindData); }
void RandomCreatBarrierAndBeginNode() { if (barrierCount > this.transform.childCount) { Debug.LogWarning("Invalid barrierCount is " + barrierCount); return; } List <int> barrierIndexList = new List <int>(); while (barrierIndexList.Count < barrierCount) { //range函数左闭,右开 int index = UnityEngine.Random.Range(0, mapInfo.nodeCount); if (!barrierIndexList.Contains(index)) { barrierIndexList.Add(index); GameObject barrierGrid = Instantiate(barrierPrefab); MapGridNode randomNode = mapInfo.GetNodeByIndex(index); barrierGrid.transform.SetParent(randomNode.gameObject.transform); barrierGrid.transform.position = barrierGrid.transform.parent.position; //障碍物节点替换原平地节点 BarrierNode barrierNode = new BarrierNode(randomNode.coordx, randomNode.coordy, randomNode.pos, randomNode.gameObject, barrierGrid); mapInfo.ChangeNode(randomNode.coordx, randomNode.coordy, barrierNode, index); } } while (beginNode == null) { int index = UnityEngine.Random.Range(0, mapInfo.nodeCount); if (!barrierIndexList.Contains(index)) { beginNode = mapInfo.GetNodeByIndex(index) as FlatNode; beginNode.isBegin = true; } } }
private void Update() { if (mapCreater.initMap) { if (Input.GetMouseButtonDown(0)) { mapCreater.GetMapInfo().CleanShowPath(); RaycastHit hitInfo; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hitInfo, 100)) { if (hitInfo.transform.name != "barrier(Clone)") { MapGridNode endNode = mapCreater.GetMapInfo().GetNodeByName(hitInfo.transform.name); PathFindMgr.RequestPathFind(mapCreater.beginNode, endNode, mapCreater.GetMapInfo(), FindComplete); Debug.Log("终点是:" + hitInfo.transform.name); } } } } }
public void ChangeNode(int x, int y, MapGridNode node, int index) { mapGridCoordIndexArray[x, y] = node; mapGridNodeList[index] = node; }