void CreateNavMap() { /* * List<NavMap> navList = new List<NavMap> (); * foreach (GameObject map in finalRegions) { * NavMap nav = map.AddComponent<NavMap> (); * nav.mapSize = new Vector2 (roomSize - 1, roomSize - 1); * nav.nodeRadius = .5f; * nav.CreateGrid (); * map.GetComponent<MapGenerator> ().self.navMap = nav; * navList.Add (nav); * } */ GameObject navigation = new GameObject(); navigation.name = "navigation"; navigation.transform.position = new Vector3(0, 0, (regionHeight / 2) * roomSize); NavMap nav = navigation.AddComponent <NavMap> (); nav.mapSize = new Vector2(regionWidth * roomSize, regionHeight * roomSize); nav.nodeRadius = .5f; nav.CreateGrid(); PathFinding finder = navigation.AddComponent <PathFinding> (); PathManager manager = navigation.AddComponent <PathManager> (); finder.requestManager = manager; }
private Vector2 rightDown; //右下角 #endregion private void Awake() { _instance = this; navGraph = new NavGraph(); //进行方向向量的初始化 pathFinder = new PathFinder(); leftUp = (Vector2.up + Vector2.left).normalized; rightUp = (Vector2.up + Vector2.right).normalized; rightDown = (Vector2.right + Vector2.down).normalized; leftDown = (Vector2.left + Vector2.down).normalized; cellSpacePartition = new CellSpacePartition <NavGraphNode>(Mathf.Abs(upBorder.position.x - downBorder.position.x) , Mathf.Abs(upBorder.position.y - downBorder.position.y) , 8, 8); CreateMap(); Debug.Log("总共有" + NavGraph.TotalV + "个顶点"); Debug.Log("总共有" + NavGraph.TotalE + "条边"); ToDebug(); }
public unsafe void OnDrawGizmos() { if (!Enable) { return; } NavMap?fetch; if (!HasSpawned(out fetch)) { return; } var navmap = (NavMap)fetch; foreach (var node in navmap.Nodes.ToArray()) { Gizmos.matrix = navmap.Transform.ToWorldMatrix; Gizmos.color = node.Walkable ? NormalColor : UnwalkableColor; var centerPos = navmap.Transform.GetWorldPos(NavMap.ToCenterPos(node.Coord, navmap.NodeSize)); if (WireCubes) { Gizmos.DrawWireCube(centerPos, new float3(navmap.NodeSize, 0, navmap.NodeSize)); } else { Gizmos.DrawCube(centerPos, new float3(navmap.NodeSize, 0, navmap.NodeSize)); } } }
public void setNavMap(NavMap nav) { this.mapBuilder.NavMap = nav; this.DataContext = mapBuilder.NavMap; setImageSource(nav.getWholeImage()); }
void Start() { caminarHacia = transform.position; pies = transform.Find("Pies").gameObject; syncAnimator = transform.GetComponent <SyncAnimator>(); escenario = FindObjectOfType <NavMap>(); }
public void shouldBeOrderableByFScore() { NavMap map = new NavMap(); NavNode a = new NavNode(new Point(2, 3)); NavNode b = new NavNode(new Point(3, 3)); NavNode c = new NavNode(new Point(1, 1)); map.Nodes.Add(a); map.Nodes.Add(b); map.Nodes.Add(c); AStarNode node = new AStarNode(a, b, 10, map); AStarNode other = new AStarNode(c, b, 10, map); List <AStarNode> set = new List <AStarNode>(); node.GScore = 10; other.GScore = 10; set.Add(other); set.Add(node); set.Sort(new FScoreComparer()); Assert.IsTrue(set[0].FScore < set[1].FScore); AStarNode first = set.First(); Assert.AreEqual(first, set[0]); Assert.AreEqual(first, node); other.GScore = 0; set.Sort(new FScoreComparer()); Assert.IsTrue(set[0].FScore < set[1].FScore); first = set.First(); Assert.AreEqual(first, set[0]); Assert.AreEqual(first, other); }
protected void SetNodeIndex(int index, NavMap map) { this.graphNodeIndex = index; pos = map.NavGraph.GetNode(index).Pos; this.transform.position = new Vector3(pos.x, pos.y, -5); }
public PathPlanner(RavenEntity entity) { this.owner = entity; map = NavMap.Instance; pathFinder = new PathFinder(); searchTimeSliced = new AStar_TimeSliced(); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { inputDeps.Complete(); Entities .WithStructuralChanges() .ForEach((Entity entity, ref NavMapCreate create) => { var size = create.Size; var nodeSize = create.NodeSize; var transform = create.Transform; var blobBuilder = new BlobBuilder(Allocator.Temp); ref var navMapBlob = ref blobBuilder.ConstructRoot <NavMapBlob>(); var nodes = blobBuilder.Allocate(ref navMapBlob.Nodes, NavMap.NodeCount(size)); navMapBlob.Size = size; navMapBlob.NodeSize = nodeSize; navMapBlob.Transform = transform; for (int x = 0; x < size.x; x++) { for (int y = 0; y < size.y; y++) { for (int z = 0; z < size.z; z++) { var coord = new int3(x, y, z); var centerPos = transform.GetWorldPos(NavMap.ToCenterPos(coord, nodeSize)); nodes[NavMap.GetIndex(coord, size)] = new NavMapNode { Coord = coord, Walkable = true, Aabb = CreateBoxAABB(centerPos, new float3(1) * nodeSize, quaternion.identity) }; } } } // Add NavMap component EntityManager.AddComponentData(entity, new NavMap { Blob = blobBuilder.CreateBlobAssetReference <NavMapBlob>(Allocator.Persistent) }); blobBuilder.Dispose(); // Remove NavMap create component EntityManager.RemoveComponent <NavMapCreate>(entity); // Push NavMapBuild (build obstacles) EntityManager.AddComponentData(entity, new NavMapBuild()); }).Run();
public void setNavMapAndShow(NavMap map) { this.navMap = map; layershowCombo.Items.Clear(); layershowCombo.Items.Add("Wall force"); for (int i = 0; i < navMap.navGrid.Count; i++) { layershowCombo.Items.Add(i); } layershowCombo.IsEnabled = true; layershowCombo.SelectedIndex = 0; this.Show(); }
//Разбитие карты на подкарты public void ShowMyDialogBox(NavigationDLL.Coords l_u, NavigationDLL.Coords r_d) { DialogResult res = MessageBox.Show("Map on one panel?", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); stopwatchLoad.Start(); if (res == DialogResult.OK) { map = new NavMap(pictureBox_navmap.Width, pictureBox_navmap.Height, l_u, r_d); } if (res == DialogResult.Cancel) { map = new NavMap(l_u, r_d, 0.0001); } }
// Use this for initialization void Start() { navMap = GameObject.Find("NavMap").GetComponent <NavMap>(); var tmpPaths = navMap.getPaths(spawnNode.id); paths = new List <NavPath>(); foreach (Node n in navMap.spawnPoints) { if (tmpPaths[navMap.pathMapping[n.id]].isPath && n.id != spawnNode.id) { paths.Add(tmpPaths[navMap.pathMapping[n.id]]); } } if (paths.Count > 0) { StartCoroutine(SpawnPrefab()); } }
private void PaintTiles(NavMap navMap) { Tilemap tilemap = GetComponent <Tilemap>(); for (int row = 0; row < map.Rows; row++) { for (int column = 0; column < map.Columns; column++) { if (navMap[row, column] == true) { tilemap.SetTile(new Vector3Int(row, column, 0), tile); } else { tilemap.SetTile(new Vector3Int(row, column, 0), null); } } } }
private static NavMap ParseNavMap(XElement element) { NavMap result = null; if (element != null && element.Name.LocalName == ELEMENT_NAVMAP) { var xNamespace = element.Name.Namespace; result = new NavMap(); var infoText = element.Element(xNamespace + ELEMENT_NAVINFO)?.Element(xNamespace + ELEMENT_TEXT).Value; if (!String.IsNullOrWhiteSpace(infoText)) { result.NavInfo = new NavInfo { Text = infoText }; } result.NavPoints = ParseNavPointList(element.Elements(xNamespace + ELEMENT_NAVPOINT), xNamespace); } return(result); }
//BackgroundWorker двупоточного поиска пути и открытия файла private void OpenFileOrTwoWaySearchBackgroubdThread(object sender, DoWorkEventArgs e) { Thread.CurrentThread.CurrentCulture = new CultureInfo("ru-UA"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-UA"); int count_proc = (int)e.Argument; switch (count_proc) { //Поиск пути case 1: { map.Drop(); pictureBox_navmap.Image = map.temp_map; tree.A.Refresh_Search(); dist = 0; dist_2 = 0; bonus_thread = new Thread(() => { way = tree.A.getWay_A(start, end, out dist, ref Not_Look, ref Look); }); bonus_thread_2 = new Thread(() => { way_2 = tree.A.getWay_A(end, start, out dist_2, ref Not_Look_2, ref Look_2, true); }); stopwatchSearch.Restart(); bonus_thread.Start(); bonus_thread_2.Start(); while (bonus_thread.IsAlive) { //Остановка поиска пути if (backgroundWorker1.CancellationPending) { bonus_thread.Abort(); if (bonus_thread_2.IsAlive) { bonus_thread_2.Abort(); } stopwatchSearch.Stop(); break; } } //bonus_thread.Join(); //bonus_thread_2.Join(); stopwatchSearch.Stop(); backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(TwoWaySearchCompleted); break; } //Загрузка карты default: { using (StreamReader myStream = new StreamReader(file_name)) { tree.A = new NavigationDLL.Graf(myStream.ReadLine().Split(' ')[1].Split('"')[1]); while (!myStream.EndOfStream) { string data = myStream.ReadLine().Split(' ')[1].Split('"')[1]; tree.A.AddNode(new GrafNode(data, '/', ';')); } } double min_lat = double.MaxValue; double min_lon = double.MaxValue; double max_lat = double.MinValue; double max_lon = double.MinValue; foreach (var item in tree.A.tree) { if (min_lat > item.Value.parametrs.coords.latitude) { min_lat = item.Value.parametrs.coords.latitude; } if (min_lon > item.Value.parametrs.coords.longitude) { min_lon = item.Value.parametrs.coords.longitude; } if (max_lat < item.Value.parametrs.coords.latitude) { max_lat = item.Value.parametrs.coords.latitude; } if (max_lon < item.Value.parametrs.coords.longitude) { max_lon = item.Value.parametrs.coords.longitude; } } NavigationDLL.Coords l_u = new NavigationDLL.Coords(max_lat, min_lon); NavigationDLL.Coords r_d = new NavigationDLL.Coords(min_lat, max_lon); //stopwatch.Stop(); //ShowMyDialogBox(l_u, r_d); //stopwatch.Start(); map = new NavMap(pictureBox_navmap.Width, pictureBox_navmap.Height, l_u, r_d); map_index = 0; map.SetAllPoint(tree.A, map_index); map.getLine(tree.A, map_index); map.setBackColor(map_index, Color.Olive); map.Save(); backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(FileOpenCompleted); break; } } }
private void GenerateNavigationMap() { NavigationMap = new NavMap(); NavigationMap.GenerateNavMap(map, SimpleNavigation); }
void Awake() { spawnNode = gameObject.GetComponent <Node>(); navMap = GameObject.Find("NavMap").GetComponent <NavMap>(); }
public Goal_Wander(RavenEntity owner, NavMap map) : base(owner) { this.map = map; }
public override void Terminate() { base.Terminate(); map = null; }
public NavigationCentereXtended() { myNavMap = new NavMap(); myPageList = new PageList(); myNavList = new NavList(); }
public NavMap buildMap(int width, int height) { if (width > 0 && height > 0) { this.DefinedWith = width; this.DefinedHeight = height; } else if (width < 0) { this.DefinedHeightProportional = height; } else if (height < 0) { this.DefinedWithProportional = width; } //Create a grid NavMap navMap = new NavMap(this.DefinedWith, this.DefinedHeight); //Define scaling factors double startX = areaRectTool.getRect().X; double startY = areaRectTool.getRect().Y; double actualWidth = areaRectTool.getRect().Width; double actualHeight = areaRectTool.getRect().Height; double defWidth = this.DefinedWith; double defHeight = this.DefinedHeight; double xScale = defWidth / actualWidth; double yScale = defHeight / actualHeight; //Gets the walls and Exits navMap.WallsList = this.wallTool.convertToSCollection(this.wallTool.LineList).getDisplace(startX, startY, xScale, yScale); navMap.ExitsList = this.exitTool.convertToSCollection(this.exitTool.LineList).getDisplace(startX, startY, xScale, yScale); //Sets the obstacles navMap.ObstaclesList = this.obsTool.convertToSCollection(this.obsTool.LineList).getDisplace(startX, startY, xScale, yScale); //Sets the collision agents List <Agent> colAgents = new List <Agent>(); foreach (Agent agent in this.colAgentTool.collisionAgents) { Agent tempAgent = agent.getDisplace(startX, startY, xScale); //Must also invert y tempAgent.Y = navMap.Height - tempAgent.Y; colAgents.Add(tempAgent); } navMap.CollisionAgents = colAgents; //Sets the shop agents List <Agent> shopAgents = new List <Agent>(); foreach (Agent agent in this.shopAgentTool.shopAgents) { Agent tempAgent = agent.getDisplace(startX, startY, xScale); //Must also invert y tempAgent.Y = navMap.Height - tempAgent.Y; shopAgents.Add(tempAgent); } navMap.ShopAgents = shopAgents; //Sets the backround and height map navMap.setBackgroundImage(imageFilePath, areaRectTool.getRect()); navMap.setHeightMapImage(heightmapFilePath, areaRectTool.getRect()); return(navMap); }
/// <summary> /// 生成寻路点 /// </summary> private static void GenerateNavPoint() { List <string> lines = new List <string>(); string objDir = $"{Application.dataPath}/{s_BuildNavMapPath.TrimStart('/').TrimEnd('/')}/"; string objPath = $"{objDir}/{SceneManager.GetActiveScene().name}_NavMesh.obj"; if (File.Exists(objPath) == false) { return; } // 读取obj using (FileStream fs = new FileStream(objPath, FileMode.Open)) { using (StreamReader sr = new StreamReader(fs)) { string line = null; while ((line = sr.ReadLine()) != null) { lines.Add(line); } } } // 处理数据 float minX = float.MaxValue; float maxX = float.MinValue; float minZ = float.MaxValue; float maxZ = float.MinValue; float maxY = float.MinValue; List <Vector3> points = new List <Vector3>(); List <Triangle> triangles = new List <Triangle>(); for (int i = 0; i < lines.Count; i++) { string line = lines[i]; string[] splits = line.Split(' '); // 获取所有点 if (splits[0] == "v") { Vector3 point = new Vector3(float.Parse(splits[1]), float.Parse(splits[2]), float.Parse(splits[3])); points.Add(point); if (point.x < minX) { minX = point.x; } if (point.x > maxX) { maxX = point.x; } if (point.z < minZ) { minZ = point.z; } if (point.z > maxZ) { maxZ = point.z; } if (point.y > maxY) { maxY = point.y; } } // 获取所有三角形 if (splits[0] == "f") { // 点索引 int aIndex = int.Parse(splits[1]); int bIndex = int.Parse(splits[2]); int cIndex = int.Parse(splits[3]); Vector3 aPoint = new Vector3(points[aIndex - 1].x, 0f, points[aIndex - 1].z); Vector3 bPoint = new Vector3(points[bIndex - 1].x, 0f, points[bIndex - 1].z); Vector3 cPoint = new Vector3(points[cIndex - 1].x, 0f, points[cIndex - 1].z); triangles.Add(new Triangle(aPoint, bPoint, cPoint)); } } // 巡航点数量 int xCount = (int)((maxX - minX) * s_PerMeterCount) + 1; int zCount = (int)((maxZ - minZ) * s_PerMeterCount) + 1; Debug.Log($"共生成寻路点: ({xCount} <=> {zCount})"); NavMap navMap = ScriptableObject.CreateInstance <NavMap>(); navMap.xCount = xCount; navMap.yCount = zCount; GameObject navMeshGo = null; GameObject.DestroyImmediate(GameObject.Find("NavMap")); if (s_GenerateGameObject) { navMeshGo = GameObject.Instantiate(Resources.Load <GameObject>(s_NavMapPath)); navMeshGo.name = "NavMap"; } for (int z = 0; z < zCount; z++) { for (int x = 0; x < xCount; x++) { NavMapPoint navMapPoint = new NavMapPoint { x = x, y = z }; float addDistance = 1f / (float)s_PerMeterCount; Vector3 generatePoint = new Vector3(minX + x * addDistance, 0f, minZ + z * addDistance); navMapPoint.position = new LVector2(new LFloat(true, generatePoint.x), new LFloat(true, generatePoint.z)); if (CheckPointInTriangle(generatePoint, triangles) == true) { navMapPoint.isWalkable = true; } else { navMapPoint.isWalkable = false; } navMap.navMapPoints.Add(navMapPoint); #region 生成GameObject,用于观察 GameObject generateGo = null; if (s_GenerateGameObject) { if (navMapPoint.isWalkable) { generateGo = GameObject.Instantiate(Resources.Load <GameObject>(s_NavWalkable)); } else { generateGo = GameObject.Instantiate(Resources.Load <GameObject>(s_NavNotWalkable)); } generateGo.transform.position = generatePoint; generateGo.transform.parent = navMeshGo.transform; generateGo.name = $"NavPoint ({x}, {z})"; } #endregion } } string navMapAsset = $"Assets/{s_BuildNavMapPath}/{SceneManager.GetActiveScene().name}_NavMap.asset"; AssetDatabase.CreateAsset(navMap, navMapAsset); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); }
/// <summary> /// 设置Astart随机游走算法 /// </summary> public void SetAstartWanderParameter(NavMap navmap, PathPlanner pathPlanner) { this.pathPlanner = pathPlanner; this.navMap = navmap; }
// Simple AStar job protected override JobHandle OnUpdate(JobHandle inputDeps) { var cmdBuffer = cmdBufferSystem.CreateCommandBuffer().ToConcurrent(); // Declare values we need var navMap = GetSingleton <NavMap>(); var count = navMap.Count; var nodeSize = navMap.NodeSize; var mapSize = navMap.Size; var transform = navMap.Transform; var ptr = navMap.NodesPtr; var neighbourRef = neighbours; // Execute job inputDeps = Entities .WithNone <Waypoint>() .WithNativeDisableUnsafePtrRestriction(ptr) .ForEach((Entity entity, int entityInQueryIndex, ref PathRequest req, ref Translation translation) => { var openList = new NativeList <int>(Allocator.Temp); var closeList = new NativeList <int>(Allocator.Temp); var costs = new NativeArray <Cost>(count, Allocator.Temp, NativeArrayOptions.UninitializedMemory); var cameFrom = new NativeArray <int>(count, Allocator.Temp, NativeArrayOptions.UninitializedMemory); for (int i = 0; i < count; i++) { costs[i] = new Cost { G = float.MaxValue, H = 0 }; cameFrom[i] = -1; } // Currently only uses X & Z coordinates (no Y-axis movement) int endIdx = NavMap.GetIndex(new float3(req.To.x, translation.Value.y, req.To.z), nodeSize, mapSize); int startIdx = NavMap.GetIndex(translation.Value, nodeSize, mapSize); var startCost = costs[startIdx]; startCost.G = 0; costs[startIdx] = startCost; openList.Add(startIdx); while (openList.Length > 0) { int currentIdx = FindNextNode(ref openList, ref costs); var currentNode = ptr[currentIdx]; // Destination is reached! if (currentIdx == endIdx) { break; } // Remove current node from Open List for (int i = 0; i < openList.Length; i++) { if (openList[i] == currentIdx) { openList.RemoveAtSwapBack(i); break; } } // Mark current as visisted closeList.Add(currentIdx); for (int i = 0; i < neighbourRef.Length; ++i) { var neighbourOffset = neighbourRef[i].Offset; var neighbourCoord = new int3(currentNode.Coord.x + neighbourOffset.x, currentNode.Coord.y, currentNode.Coord.z + neighbourOffset.y); var neighbourDst = neighbourRef[i].Distance; // If node is outside of map if (!NavMap.NotOutOfBounds(neighbourCoord, mapSize)) { continue; } int neighbourIdx = NavMap.GetIndex(neighbourCoord, mapSize); NavMapNode neighbourNode = ptr[neighbourIdx]; // If node is not walkable or in closed set (already searched) if (closeList.Contains(neighbourIdx) || !neighbourNode.Walkable) { continue; } var astarCost = new Cost(costs[currentIdx].G, Heuristic(currentNode.Coord, neighbourNode.Coord)); if (astarCost.F < costs[neighbourIdx].G) { cameFrom[neighbourIdx] = currentIdx; costs[neighbourIdx].Set(astarCost.F, costs[neighbourIdx].H); var neighbourCost = costs[neighbourIdx]; neighbourCost.G = astarCost.F; costs[neighbourIdx] = neighbourCost; if (!openList.Contains(neighbourIdx)) { openList.Add(neighbourIdx); } } } } var cursor = endIdx; if (cameFrom[cursor] != -1) { // We Found a path var waypoints = cmdBuffer.AddBuffer <Waypoint>(entityInQueryIndex, entity); while (cameFrom[cursor] != -1) { var coord = ptr[cursor].Coord; // Use exact requested position for end node // TODO: this may not be a good idea var worldPos = cursor == endIdx ? req.To : transform.GetWorldPos(NavMap.ToCenterPos(coord, nodeSize)); var pathPoint = new float3(worldPos.x, translation.Value.y, worldPos.z); waypoints.Add(new Waypoint() { Value = pathPoint }); cursor = cameFrom[cursor]; } } cmdBuffer.RemoveComponent <PathRequest>(entityInQueryIndex, entity); openList.Dispose(); closeList.Dispose(); costs.Dispose(); cameFrom.Dispose(); }).Schedule(inputDeps); cmdBufferSystem.AddJobHandleForProducer(inputDeps); inputDeps.Complete(); return(inputDeps); }
/** * Paint a NavMap as an overlay of the terrain map, with the tile colour * determined by the MapActionState. */ public void PaintOverlay(NavMap navMap, MapActionState state) { SetTileColour(state); PaintTiles(navMap); }