static string GetAndEnsureTargetPath(NavMeshSurface surface) { // Create directory for the asset if it does not exist yet. var activeScenePath = surface.gameObject.scene.path; var targetPath = "Assets"; if (!string.IsNullOrEmpty(activeScenePath)) { targetPath = Path.Combine(Path.GetDirectoryName(activeScenePath), Path.GetFileNameWithoutExtension(activeScenePath)); } else { var prefabStage = PrefabStageUtility.GetPrefabStage(surface.gameObject); var isPartOfPrefab = prefabStage != null && prefabStage.IsPartOfPrefabContents(surface.gameObject); if (isPartOfPrefab) { #if UNITY_2020_1_OR_NEWER var assetPath = prefabStage.assetPath; #else var assetPath = prefabStage.prefabAssetPath; #endif if (!string.IsNullOrEmpty(assetPath)) { var prefabDirectoryName = Path.GetDirectoryName(assetPath); if (!string.IsNullOrEmpty(prefabDirectoryName)) { targetPath = prefabDirectoryName; } } } } if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } return(targetPath); }
static NavMeshData GetNavMeshAssetToDelete(NavMeshSurface navSurface) { #pragma warning disable CS0618 // Type or member is obsolete var prefabType = PrefabUtility.GetPrefabType(navSurface); #pragma warning restore CS0618 // Type or member is obsolete #pragma warning disable CS0618 // Type or member is obsolete #pragma warning disable CS0618 // Type or member is obsolete if (prefabType == PrefabType.PrefabInstance || prefabType == PrefabType.DisconnectedPrefabInstance) #pragma warning restore CS0618 // Type or member is obsolete #pragma warning restore CS0618 // Type or member is obsolete { // Don't allow deleting the asset belonging to the prefab parent #pragma warning disable CS0618 // Type or member is obsolete var parentSurface = PrefabUtility.GetPrefabParent(navSurface) as NavMeshSurface; #pragma warning restore CS0618 // Type or member is obsolete if (parentSurface && navSurface.navMeshData == parentSurface.navMeshData) { return(null); } } return(navSurface.navMeshData); }
//构造函数,只有第一个房子用得到,后面用CreateNextRoom就行了 public Room(int id, GameObject roomprefab, Vector3 p, MobGroup mobgroup) { if (StaticRoompPefab == null) { StaticRoompPefab = roomprefab; } this.mg = mobgroup; roomid = id; this.roomgo = GameObject.Instantiate(StaticRoompPefab, p, Quaternion.identity); //第一次调用的时候,nextroomposition为Vector3.Zero,后面的房间才需要计算 roomgo.name += " - " + roomid.ToString(); rc = roomgo.GetComponent<RoomController>(); nms = rc.Floor.GetComponent<NavMeshSurface>(); bc = roomgo.GetComponent<BoxCollider>(); bc.enabled = true; rc.thisroomid = id; this.CloseAll(); nms.BuildNavMesh(); nms.UpdateNavMesh(nms.navMeshData); this.directionToNextRoom = CalculateNextRoomDirection(); this.nextroomposition = CalculateNextRoomPosition(); roomdic.Add(this.roomid, this); }
void StoreNavMeshDataIfInPrefab(NavMeshSurface surfaceToStore) { var prefabStage = PrefabStageUtility.GetPrefabStage(surfaceToStore.gameObject); var isPartOfPrefab = prefabStage != null && prefabStage.IsPartOfPrefabContents(surfaceToStore.gameObject); if (!isPartOfPrefab) { return; } // check if data has already been stored for this surface foreach (var storedAssetInfo in m_PrefabNavMeshDataAssets) { if (storedAssetInfo.surface == surfaceToStore) { return; } } if (m_PrefabNavMeshDataAssets.Count == 0) { PrefabStage.prefabSaving -= DeleteStoredNavMeshDataAssetsForOwnedSurfaces; PrefabStage.prefabSaving += DeleteStoredNavMeshDataAssetsForOwnedSurfaces; PrefabStage.prefabStageClosing -= ForgetUnsavedNavMeshDataChanges; PrefabStage.prefabStageClosing += ForgetUnsavedNavMeshDataChanges; } var isDataOwner = true; if (PrefabUtility.IsPartOfPrefabInstance(surfaceToStore) && !PrefabUtility.IsPartOfModelPrefab(surfaceToStore)) { var basePrefabSurface = PrefabUtility.GetCorrespondingObjectFromSource(surfaceToStore) as NavMeshSurface; isDataOwner = basePrefabSurface == null || surfaceToStore.navMeshData != basePrefabSurface.navMeshData; } m_PrefabNavMeshDataAssets.Add(new SavedPrefabNavMeshData { surface = surfaceToStore, navMeshData = isDataOwner ? surfaceToStore.navMeshData : null }); }
public bool IsSurfaceBaking(NavMeshSurface surface) { if (surface == null) { return(false); } foreach (var oper in m_BakeOperations) { if (oper.surface == null || oper.bakeOperation == null) { continue; } if (oper.surface == surface) { return(true); } } return(false); }
public void BuildNavMesh() { int agentTypeCount = NavMesh.GetSettingsCount(); if (agentTypeCount < 1) { return; } for (int i = 0; i < navMeshElements.Count; ++i) { if(navMeshElements[i]) navMeshElements[i].transform.SetParent(gameObject.transform, true); } for (int i = 0; i < agentTypeCount; ++i) { NavMeshBuildSettings settings = NavMesh.GetSettingsByIndex(i); NavMeshSurface navMeshSurface = gameObject.AddComponent<NavMeshSurface>(); navMeshSurface.agentTypeID = settings.agentTypeID; NavMeshBuildSettings actualSettings = navMeshSurface.GetBuildSettings(); navMeshSurface.useGeometry = NavMeshCollectGeometry.PhysicsColliders; // or you can use RenderMeshes navMeshSurface.BuildNavMesh(); } }
public void SpawnFloorContent(int floorCount) { if (floorCount == 0) { contentIndex = 0; } else if (floorCount < 5) { contentIndex = Random.Range(1, indexOfEasy); } else { contentIndex = Random.Range(1, PremadeFloorContentList.Length); } floorContent = Instantiate( PremadeFloorContentList[contentIndex], transform.position, Quaternion.identity, transform.root ); foreach (Transform child in floorContent.transform) { if (child.CompareTag("Enemy")) { enemies.Add(child.gameObject); } if (child.CompareTag("PlayerSpawn")) { playerSpawnPoint = child.gameObject; playerSpawnPoint.GetComponent <Renderer>().enabled = false; } } nav = GetComponent <NavMeshSurface>(); nav.BuildNavMesh(); }
public void Init() { collisionObject = new GameObject(); collisionObject.name = "Collision Mesh"; collisionObject.transform.SetParent(gameObject.transform); collisionObject.transform.localPosition = new Vector3(0, 0, 0); terrainMesh = new Mesh(); terrainMesh.name = "TerrainCollisionMesh"; chunk = GetComponent <TerrainChunk>(); meshFilter = collisionObject.AddComponent <MeshFilter>(); meshCollider = collisionObject.AddComponent <MeshCollider>(); meshRenderer = collisionObject.AddComponent <MeshRenderer>(); meshRenderer.enabled = false; meshFilter.sharedMesh = terrainMesh; meshCollider.sharedMesh = terrainMesh; vertices = new List <Vector3>(); triangles = new List <int>(); navMeshSurface = collisionObject.AddComponent <NavMeshSurface>(); }
/// <summary> /// Initial awake function. /// Used to set all <see langword="static"/> fields. /// Also loads all required resources via the <see cref="ResourceManager"/> /// </summary> void Awake() { NavMeshSurf = GetComponent <NavMeshSurface>(); IsPlaying = true; Debug.Log(Application.persistentDataPath); //ZeroFormatter.Formatters.Formatter.Register Game = this; DebugGUI = GetComponent <DebugGUI>(); WorldManager = transform.Find("WorldManager").GetComponent <WorldManager>(); EntityManager = transform.Find("EntityManager").GetComponent <EntityManager>(); PlayerManager = transform.Find("PlayerManager").GetComponent <PlayerManager>(); QuestManager = GetComponent <QuestManager>(); GUIManager = GetComponentInChildren <GUIManager>(); EventManager = new EventManager(); Console = GetComponentInChildren <Console>(); ResourceManager.LoadAllResources(); LoadSave = new LoadSave("test"); }
public void BuildNavMesh() { Awake(); // remove existing navMeshSurfaces foreach (NavMeshSurface navMeshSurface in _navMeshRoot.GetComponents <NavMeshSurface>()) { Destroy(navMeshSurface); } int agentTypeCount = UnityEngine.AI.NavMesh.GetSettingsCount(); if (agentTypeCount < 1) { return; } for (int i = 0; i < agentTypeCount; ++i) { NavMeshBuildSettings settings = UnityEngine.AI.NavMesh.GetSettingsByIndex(i); NavMeshSurface navMeshSurface = _navMeshRoot.AddComponent <NavMeshSurface>(); navMeshSurface.AgentTypeId = settings.agentTypeID; NavMeshBuildSettings actualSettings = navMeshSurface.GetBuildSettings(); navMeshSurface.useGeometry = NavMeshCollectGeometry.RenderMeshes; // or you can use RenderMeshes //navMeshSurface.layerMask = true; // remove existing agents from the navmesh layermask navMeshSurface.layerMask -= LayerMask.GetMask("Agents"); navMeshSurface.layerMask -= LayerMask.GetMask("Ignore Raycast"); navMeshSurface.buildHeightMesh = true; navMeshSurface.BuildNavMesh(); } this._navMeshInitialized = true; }
// Permet de créer automatiquement la surface du navmesh à partir des données de la map private void CreateSurface() { // Création de la vue en fonction des Datas // GameObject surface = Instantiate(prefabSurface); GameObject surface = (GameObject)PrefabUtility.InstantiatePrefab(prefabSurface); surface.transform.SetParent(navContainer.transform); // Calcul de la position de la surface. Vector3 posSurface = surface.transform.position; posSurface.x = mapData.width / 2; posSurface.z = mapData.height / 2; // Test si width impair pour ajout de declage sur la position. if (mapData.width % 2 != 0) { posSurface.x += 0.5f; } if (mapData.height % 2 != 0) { posSurface.z += 0.5f; } surface.transform.position = posSurface; // Calcul du scale de la surface. Vector3 scaleSurface = surface.transform.localScale; scaleSurface.x = mapData.width; scaleSurface.z = mapData.height; surface.transform.localScale = scaleSurface; // Bake NavMesh NavMeshSurface surfaceComponent = surface.GetComponent <NavMeshSurface>(); surfaceComponent.BuildNavMesh(); surfaceComponent.transform.SetAsFirstSibling(); }
public TerrainChunk(Vector2 coord, HeightMapSettings heightMapSettings, MeshSettings meshSettings, LODInfo[] detailLevels, int colliderLODIndex, Transform parent, Transform viewer, Material material) { this.coord = coord; this.detailLevels = detailLevels; this.colliderLODIndex = colliderLODIndex; this.heightMapSettings = heightMapSettings; this.meshSettings = meshSettings; this.viewer = viewer; this.surface = NavMeshSurface.FindObjectOfType <NavMeshSurface>(); sampleCentre = coord * meshSettings.meshWorldSize / meshSettings.meshScale; Vector2 position = coord * meshSettings.meshWorldSize; bounds = new Bounds(position, Vector2.one * meshSettings.meshWorldSize); meshObject = new GameObject("Terrain Chunk"); meshRenderer = meshObject.AddComponent <MeshRenderer>(); meshFilter = meshObject.AddComponent <MeshFilter>(); meshCollider = meshObject.AddComponent <MeshCollider>(); meshRenderer.material = material; meshObject.transform.position = new Vector3(position.x, 0, position.y); meshObject.transform.parent = parent; SetVisible(false); lodMeshes = new LODMesh[detailLevels.Length]; for (int i = 0; i < detailLevels.Length; i++) { lodMeshes[i] = new LODMesh(detailLevels[i].lod); lodMeshes[i].updateCallback += UpdateTerrainChunk; if (i == colliderLODIndex) { lodMeshes[i].updateCallback += UpdateCollisionMesh; } } maxViewDst = detailLevels [detailLevels.Length - 1].visibleDstThreshold; }
/// <summary> /// 加载关卡配置 /// </summary> /// <returns></returns> private void LoadLevelConfig() { // 加载配置 var resMgr = Game.GetManager <GResManager>(); var bundleName = "levels/scenes/" + m_levelName.ToLower(); var bundle = resMgr.LoadAssetBundle(bundleName); var mapTextAsset = bundle.LoadAsset("Map.xml") as TextAsset; SecurityParser parser = new SecurityParser(); parser.LoadXml(mapTextAsset.text); m_xml = parser.ToXml(); // navmesh var navmeshPrefab = bundle.LoadAsset("Navmesh.prefab") as GameObject; var navGo = GameObject.Instantiate(navmeshPrefab) as GameObject; navGo.transform.position = Vector3.zero; m_navMeshSurface = navGo.GetComponent <NavMeshSurface>(); m_navMeshSurface.layerMask = 1 << LayerMask.NameToLayer(LevelFunctionType.Ground.ToString()); resMgr.UnLoadAssetBundle(bundleName); }
// called by startcoroutine whenever you want to build the navmesh IEnumerator BuildNavmesh(NavMeshSurface surface) { // get the data for the surface var data = InitializeBakeData(surface); // start building the navmesh ao = surface.UpdateNavMesh(data); loading = true; // wait until the navmesh has finished baking yield return(ao); Debug.Log("finished"); // you need to save the baked data back into the surface surface.navMeshData = data; // call AddData() to finalize it surface.AddData(); loading = false; i.fillAmount = 0; text.SetActive(false); OnNavBake.Invoke(); }
void Start() { player_detect_speed = EnemyService.get_detect_interval(entity.rank); nmSurface = GameObject.FindGameObjectWithTag("SystemManager").GetComponent <NavMeshSurface>(); nmAgent = GetComponent <NavMeshAgent>(); animator = GetComponent <Animator>(); outline = GetComponentInChildren <Outline>(); collider = GetComponent <Collider>(); Observable.Interval(TimeSpan.FromMilliseconds(player_detect_speed)).Subscribe(x => { // プレイヤー位置を取得する player_position = PlayerService.position(); }).AddTo(this); character_control = true; DoMoveMode(); //Debug.Log("EnemyController : id : " + id); //Debug.Log("EnemyController : entity.name : " + entity.name); //this.UpdateAsObservable().ObserveOnMainThread().Subscribe(x => { //}); }
// Start is called before the first frame update void Start() { GameObject go = GameObject.FindWithTag("PlayerSpawn"); GameObject player = GameObject.FindWithTag("Player"); player.transform.position = go.transform.position; Destroy(go); GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy"); foreach (var e in enemies) { e.GetComponent <PauseHandler>().isPaused = false; } player.GetComponent <PauseHandler>().isPaused = false; NavMeshSurface nav = FindObjectOfType <NavMeshSurface>(); nav.BuildNavMesh(); //Debug.Log("Test setup complete"); }
NavMeshData GetNavMeshAssetToDelete(NavMeshSurface navSurface) { if (PrefabUtility.IsPartOfPrefabInstance(navSurface) && !PrefabUtility.IsPartOfModelPrefab(navSurface)) { // Don't allow deleting the asset belonging to the prefab parent var parentSurface = PrefabUtility.GetCorrespondingObjectFromSource(navSurface) as NavMeshSurface; if (parentSurface && navSurface.navMeshData == parentSurface.navMeshData) { return(null); } } // Do not delete the NavMeshData asset referenced from a prefab until the prefab is saved var prefabStage = PrefabStageUtility.GetPrefabStage(navSurface.gameObject); var isPartOfPrefab = prefabStage != null && prefabStage.IsPartOfPrefabContents(navSurface.gameObject); if (isPartOfPrefab && IsCurrentPrefabNavMeshDataStored(navSurface)) { return(null); } return(navSurface.navMeshData); }
public void Start() { Vector3 fwd = exitPoint.TransformDirection(Vector3.forward); surface = GameObject.FindWithTag("NavMeshManager").GetComponent <NavMeshSurface>(); if (Physics.Raycast(transform.position, fwd, out RaycastHit hit, 1, layerMaskInteract.value)) { if (hit.collider.CompareTag("Object")) { hit.collider.gameObject.SetActive(false); gameObject.SetActive(false); surface.BuildNavMesh(); } } canvas = transform.Find("Canvas").gameObject; canvas.SetActive(false); setupChildSpawner("ImageSmallRoom"); setupChildSpawner("ImageBigRoom"); setupChildSpawner("ImageHangar"); }
void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode) { if (theOne) { if (am == null) { am = AudioManager.instance; } if (scene == SceneManager.GetSceneByName("MainMenu")) { am.StopAll(); am.Play("GameMenu"); } if (scene == SceneManager.GetSceneByName("Tower Defense Game")) { am.StopAll(); am.Play("BGM"); castleHp = GameObject.Find("Castle").GetComponentInChildren <Health>(); surface = GameObject.Find("NavMesh").GetComponent <NavMeshSurface>(); CreateMap(); if (loadingData) { loadingData = false; castleHp.setHealth(data.castleHealth); } else { ResetValues(); } theGUI = GameObject.Find("GUIText").GetComponent <Text>(); setGUI(); } } }
// Start is called before the first frame update public void GenerateLevel() { //delete previous map map = new Arena[5, 5]; if (mapObjects != null) { foreach (GameObject tile in mapObjects) { GameObject.Destroy(tile); } } surface = FindObjectOfType <NavMeshSurface>(); for (int i = 0; i < map.GetLength(0); i++) { for (int j = 0; j < map.GetLength(1); j++) { map[i, j] = new Arena(); } } if (!useSeed) { System.Random seedGenerator = new System.Random(); seed = seedGenerator.Next(); } System.Random rand = new System.Random(seed); Debug.Log("Seed used: " + seed); if (GenerateMap(rand)) { PopulateMap(rand); } surface.BuildNavMesh(); }
void Awake() { if (ThisIsTheLobbyLevel) { if (LobbyLevel != null && LobbyLevel != this) { Debug.LogWarning("Multiple Level objects set as the lobby! check: " + LobbyLevel.gameObject.name + ", " + gameObject.name); } else { LobbyLevel = this; } } //TODO: ensure Spawner samples available for holes and towns NavSurface = GetComponentInChildren <NavMeshSurface>(); transform.position = Vector3.zero; //center from spread-out viewing positions LevelStartPosition _positionObject = GetComponentInChildren <LevelStartPosition>(true); _positionObject.gameObject.SetActive(false); }
public void Bake() { #if UNITY_EDITOR if (!Application.isPlaying) { _surface = GetComponent <NavMeshSurface>(); } #endif var settings = NavMesh.GetSettingsByID(NavMeshSurfaceComponent.agentTypeID); _agentRadius = settings.agentRadius; Clear(); SetNavMeshEdges(NavMesh.CalculateTriangulation(), invertFacingNormal, dontAlignYAxis); SpawnLinks(); #if UNITY_EDITOR if (!Application.isPlaying) { EditorSceneManager.MarkSceneDirty(gameObject.scene); } #endif }
void Start() { agent = FindObjectOfType <NavMeshAgent>(); agent.enabled = false; surface = FindObjectOfType <NavMeshSurface>(); path = new NavMeshPath(); //设置导航线的颜色宽度 line = FindObjectOfType <LineRenderer>(); line.material = new Material(Shader.Find("Sprites/Default")); line.positionCount = 0; line.widthMultiplier = 0.3f; Gradient gradient = new Gradient(); gradient.SetKeys( new GradientColorKey[] { new GradientColorKey(Color.blue, 0.0f), new GradientColorKey(Color.blue, 1.0f) }, new GradientAlphaKey[] { new GradientAlphaKey(1f, 0.0f), new GradientAlphaKey(1f, 1.0f) }); line.colorGradient = gradient; }
private void _CreatePlayer() { EntityManager entityManager = World.Active.EntityManager; EntityArchetype terrainType = entityManager.CreateArchetype( typeof(PlayerComponent), typeof(Translation), typeof(RenderMesh), typeof(LocalToWorld) ); Entity entity = entityManager.CreateEntity(terrainType); var position = new float3(Random.Range(1, 50), 0, Random.Range(1, 50)); entityManager.SetComponentData(entity, new Translation { Value = position }); entityManager.SetSharedComponentData(entity, new RenderMesh { mesh = PlayerMesh, material = PlayerMaterial }); NavMeshAgent = GameObject.FindObjectOfType <NavMeshAgent>(); NavMeshSurface = GameObject.FindObjectOfType <NavMeshSurface>(); }
public void generateNavMesh() { /*UnityEngine.AI.NavMesh.RemoveAllNavMeshData(); * nmd = new NavMeshData(0); * * UnityEngine.AI.NavMeshBuildSettings b = NavMesh.GetSettingsByIndex(0); * Debug.Log("Building for: "+NavMesh.GetSettingsNameFromID(b.agentTypeID)); * UnityEngine.AI.NavMeshBuildSource bs = new UnityEngine.AI.NavMeshBuildSource(); * Terrain t = TerrainObject.GetComponent<Terrain>(); * bs.shape = NavMeshBuildSourceShape.Terrain; * bs.sourceObject = t; * bs.transform = Matrix4x4.TRS(t.transform.position, Quaternion.identity, Vector3.one); * bs.area = 0; * List<NavMeshBuildSource> nmbs = new List<UnityEngine.AI.NavMeshBuildSource>(new UnityEngine.AI.NavMeshBuildSource[]{bs}); * * nmd = UnityEngine.AI.NavMeshBuilder.BuildNavMeshData(b,nmbs,new Bounds(Vector3.zero, t.transform.position),t.transform.position,Quaternion.identity); * NavMesh.AddNavMeshData(nmd); * AsyncOperation o = UnityEngine.AI.NavMeshBuilder.UpdateNavMeshDataAsync(nmd,b,nmbs,new Bounds(Quantize(t.gameObject.transform.position, 0.1f * new Vector3(80.0f, 20.0f, 80.0f)), new Vector3(80.0f, 20.0f, 80.0f))); * Debug.Log("Mesh Generation started."); * o.completed += MeshFinished; * * foreach (NavMeshAgent a in this.transform.root.GetComponentsInChildren<NavMeshAgent>()){ * * }*/ NavMeshSurface nms = TerrainObject.GetComponent <NavMeshSurface>(); if (nms == null) { TerrainObject.AddComponent(typeof(NavMeshSurface)); nms = TerrainObject.GetComponent <NavMeshSurface>(); } nms.layerMask = LayerMask.GetMask(new string[] { "Terrain" }); nms.BuildNavMesh(); //UnityEngine.AI.NavMeshData nmd = UnityEngine.AI.NavMeshBuilder.BuildNavMeshData(b,new List<UnityEngine.AI.NavMeshBuildSource>(new UnityEngine.AI.NavMeshBuildSource[]{bs}),new Bounds(new Vector3(0,0,0),new Vector3(100,100,100)),new Vector3(0,0,0),Quaternion.identity); }
static void RenderBoxGizmoSelected(NavMeshSurface navSurface, GizmoType gizmoType) { RenderBoxGizmo(navSurface, gizmoType, true); }
public override void SetupAgent(Agent agent) { if (surface == null) { surface = FindObjectOfType <NavMeshSurface>(); if (surface == null) { Debug.LogError(agent.name + ": Is using UnityNavMeshMT which requires a NavMeshSurface in the Scene. Please add."); return; } } // Needed to clear out Dicts after playing for AgentView Editor Window if (!Application.isPlaying && navMeshAgents != null && navMeshAgents.ContainsKey(agent)) { OnEnable(); } NavMeshAgent navMeshAgent = agent.GetComponent <NavMeshAgent>(); if (navMeshAgent == null) { Debug.LogError(agent.name + ": Is using UnityNavMeshMT which requires a NavMeshAgent Component. Please add to Agent."); return; } else if (Mathf.Abs(navMeshAgent.baseOffset) > .25f) { Debug.LogWarning("NavMeshAgent has a large baseOffset - Please make sure Agent's root transform is on the NavMesh. " + "(It should be on the ground at the Agent's feet.)"); } navMeshAgents.Add(agent, navMeshAgent); pathCache.Add(agent, new Dictionary <Vector3, PathCache>()); agent.movementType.NavMeshAgentUpdateRotation(agent, navAgentUpdateRotation); agent.movementType.NavMeshAgentUpdatePosition(agent, navAgentUpdatePosition); if (useRootMotion) { RootMotionMovement rootMotionMovement = agent.GetComponent <RootMotionMovement>(); if (rootMotionMovement == null) { Debug.LogError(agent.name + ": Using UnityNavMeshMT with Root Motion which requires a RootMotionMovement component. " + "Please add to agent."); } else { rootMotionMovement.Initialize(agent); } } else { NonRootMotionMovement nonRootMotionMovement = agent.GetComponent <NonRootMotionMovement>(); if (nonRootMotionMovement == null) { Debug.LogError(agent.name + ": Using UnityNavMeshMT with No Root Motion which requires a NonRootMotionMovement component. " + "Please add to agent."); } else { nonRootMotionMovement.Initialize(agent); } } }
public void GenerateMap() { currentMap = maps[mapIndex]; tileMap = new Transform[currentMap.mapSize.x, currentMap.mapSize.y]; System.Random prng = new System.Random(currentMap.seed); // Generating coords allTilesCoords = new List <Coord>(); for (int x = 0; x < currentMap.mapSize.x; x++) { for (int y = 0; y < currentMap.mapSize.y; y++) { allTilesCoords.Add(new Coord(x, y)); } } shuffledTileCoords = new Queue <Coord>(Utility.ShuffleArray <Coord>(allTilesCoords.ToArray(), currentMap.seed)); // Create map holder obj string holderName = "Generated Map"; if (transform.Find(holderName)) { DestroyImmediate(transform.Find(holderName).gameObject); } Transform mapHolder = new GameObject(holderName).transform; mapHolder.SetParent(transform); // Spawning tiles for (int x = 0; x < currentMap.mapSize.x; x++) { for (int y = 0; y < currentMap.mapSize.y; y++) { Vector3 tilePosition = CoordToPosition(x, y); Transform newTile = Instantiate <Transform>(tilePrefab, tilePosition, Quaternion.Euler(Vector3.right * 90)); newTile.SetParent(mapHolder); newTile.localScale = Vector3.one * (1 - outlinePercent) * tileSize; tileMap[x, y] = newTile.transform; } } // Spawing obstacles bool[,] obstacleMap = new bool[(int)currentMap.mapSize.x, (int)currentMap.mapSize.y]; int obstacleCount = (int)(currentMap.mapSize.x * currentMap.mapSize.y * currentMap.obstaclePercent); int currentObstacleCount = 0; List <Coord> allOpenCoords = new List <Coord>(allTilesCoords); for (int i = 0; i < obstacleCount; i++) { Coord randomCoord = GetRandomCoord(); obstacleMap[randomCoord.x, randomCoord.y] = true; currentObstacleCount++; if (randomCoord != currentMap.mapCentre && MapIsFullyAccessible(obstacleMap, currentObstacleCount)) { float obstacleHeight = Mathf.Lerp(currentMap.minObstacleHeight, currentMap.maxObstacleHeight, (float)prng.NextDouble()); Vector3 obstaclePosition = CoordToPosition(randomCoord.x, randomCoord.y); Transform newObstacle = Instantiate <Transform>(obstaclePrefab, obstaclePosition + Vector3.up * obstacleHeight / 2f, Quaternion.identity); newObstacle.SetParent(mapHolder); newObstacle.localScale = new Vector3((1 - outlinePercent) * tileSize, obstacleHeight, (1 - outlinePercent) * tileSize); Renderer obstacleRenderer = newObstacle.GetComponent <Renderer>(); Material obstacleMaterial = new Material(obstacleRenderer.sharedMaterial); float colorPercent = randomCoord.y / (float)currentMap.mapSize.y; obstacleMaterial.color = Color.Lerp(currentMap.foregroundColor, currentMap.backgroundColor, colorPercent); obstacleRenderer.sharedMaterial = obstacleMaterial; allOpenCoords.Remove(randomCoord); } else { obstacleMap[randomCoord.x, randomCoord.y] = false; currentObstacleCount--; } } shuffledOpenTileCoords = new Queue <Coord>(Utility.ShuffleArray <Coord>(allOpenCoords.ToArray(), currentMap.seed)); mapFloor.localScale = new Vector3(currentMap.mapSize.x * tileSize, currentMap.mapSize.y * tileSize); navMeshFloor.localScale = new Vector3(maxMapSize.x, maxMapSize.y) * tileSize; if (navMeshSurface == null) { navMeshSurface = GetComponent <NavMeshSurface>(); } navMeshSurface.BuildNavMesh(); }
void LoadNavMesh() { surface = FindObjectOfType <NavMeshSurface>(); surface.BuildNavMesh(); }
private void Awake() { navMeshSurface = GetComponent <NavMeshSurface>(); }