Ejemplo n.º 1
0
        /// <summary>
        /// Bakes the Unity NavMesh on created NavMeshObjects.
        /// </summary>
        public void BakeNavMesh()
        {
            //loop over renderers and enable them for the baking process,
            //as otherwise the NavMeshBuilder will ignore them
            List <Renderer> disabledObjects = new List <Renderer>();

            {
                var __array1       = Object.FindObjectsOfType(typeof(Renderer));
                var __arrayLength1 = __array1.Length;
                for (int __i1 = 0; __i1 < __arrayLength1; ++__i1)
                {
                    var item = (Renderer)__array1[__i1];
                    {
                        if (GameObjectUtility.AreStaticEditorFlagsSet(item.gameObject, StaticEditorFlags.NavigationStatic) &&
                            !item.enabled)
                        {
                            disabledObjects.Add(item);
                            item.renderer.enabled = true;
                        }
                    }
                }
            }
            //trigger navmesh builder
            NavMeshBuilder.BuildNavMesh();
            //re-enable disabled renderers
            disabledObjects.ForEach(obj => obj.enabled = false);

            ShowNotification("NavMesh successfully built.");
        }
Ejemplo n.º 2
0
 void BuildAllNavMesh(float agentRadius)
 {
     map.SetActive(false);
     ClearTmp();
     SetAgentRadius(agentRadius);
     xingzouceng.GetComponent <Renderer>().enabled = true;
     if (feixingceng != null)
     {
         feixingceng.GetComponent <Renderer>().enabled = true;
     }
     if (qinggong != null)
     {
         qinggong.GetComponent <Renderer>().enabled = true;
     }
     NavMeshBuilder.ClearAllNavMeshes();
     NavMeshBuilder.BuildNavMesh();
     xingzouceng.GetComponent <Renderer>().enabled = false;
     if (feixingceng != null)
     {
         feixingceng.GetComponent <Renderer>().enabled = false;
     }
     if (qinggong != null)
     {
         qinggong.GetComponent <Renderer>().enabled = false;
     }
     map.SetActive(true);
 }
#pragma warning restore 0649
        #endregion

        private void Awake()
        {
            Terrain terrain = GetComponent <Terrain> ();

            terrain.terrainData = GenerateTerrain(terrain.terrainData);
            NavMeshBuilder.BuildNavMesh();
        }
Ejemplo n.º 4
0
    // Use this for initialization
    void Start()
    {
        Debug.Log("Editor mode");
        //Get all GameObjects with tag "Wall"
        if (Wall == null)
        {
            Wall = GameObject.FindGameObjectsWithTag("Wall");
        }
        if (Door == null)
        {
            Door = GameObject.FindGameObjectsWithTag("Door");
        }

        plane = GameObject.CreatePrimitive(PrimitiveType.Plane);           //The plane(GameObject) that will cloned

        // Instantiate planes at base of all walls and doors in map/scene
        foreach (GameObject w in Wall)
        {
            instantiateFloorPlanes(w);
        }
        foreach (GameObject d in Door)
        {
            createDoorPlanes(d);
        }

        NavMeshBuilder.BuildNavMesh();                                  // BAKE THE NAVMESH
    }
Ejemplo n.º 5
0
    // Use this for initialization
    void Start()
    {
        //wall = GameObject.FindGameObjectWithTag("Base_Wall");
        floor = new GameObject("Floor");
        if (file != null)
        {
            Debug.Log("JSON file exists.");
            myJSON = JSONNode.Parse(file.text);
        }
        else
        {
            Debug.Log("JSON file is not existing.");
        }

        Debug.Log(myJSON.Count);
        Debug.Log(myJSON.AsObject.GetKeys().Count);

        ArrayList roomNames = myJSON.AsObject.GetKeys();

        for (int i = 0; i < myJSON.Count; i++)
        {
            //string name = (string)roomNames[i];
            Debug.Log("Creating " + i + "th Room.");
            createRoomFromJSON(myJSON[i],
                               (string)roomNames[i]);
        }
#if UNITY_EDITOR
        NavMeshBuilder.BuildNavMesh();
#endif
    }
Ejemplo n.º 6
0
 private void Bake()
 {
     if (RefreshPreviewMesh())
     {
         NavMeshBuilder.BuildNavMesh();
     }
 }
        //------------------------------------------------------------------------------------------------------------------
        void Start()
        {
//#if UNITY_EDITOR
//            UnityEditor.SceneView.FocusWindowIfItsOpen(typeof(UnityEditor.SceneView));
//#endif

            this.m_charProxy = GameObject.Find("GAMEOBJ_CharProxy");
            this.m_mainPath  = "Prefab/_Level_A/";

#if UNITY_EDITOR
            LoadCrossPieces();
            LoadCornerPieces();
            LoadLinePieces();
            LoadDeadEndPieces();
            LoadTriplePieces();
            LoadNonePiece();
            CreateRandomDungeon();
            MoveAllMapLinkedToFirstPiecePivot(0, 0);
            ScrambleTileVersions();
            ModifyTilePatterns();
            PopulatePiecesAtDungeon();
            PlaceAgentAtStartPointInNavmesh();

            NavMeshBuilder.ClearAllNavMeshes();
            NavMeshBuilder.BuildNavMesh();
#endif
        }
Ejemplo n.º 8
0
        public override void Execute()
        {
            Retain();
            NavMeshBuilder.ClearAllNavMeshes();

            NavMeshBuilder.BuildNavMesh();
            Release();
        }
    public void NavmeshBenchmark()
    {
        double TimeBefore = EditorApplication.timeSinceStartup;

        NavMeshBuilder.BuildNavMesh();
        double TimeElapsed = EditorApplication.timeSinceStartup - TimeBefore;

        StoreResults(TimeElapsed);
    }
Ejemplo n.º 10
0
        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            EditorGUILayout.Space();

            EditorGUILayout.LabelField("Current Vertices: " + navMeshObject.vertices.Count);

            EditorGUILayout.LabelField("Current Triangles: " + navMeshObject.triangles.Count / 3);


            if (navMeshObject.editable)
            {
                GUI.color = Color.yellow;
            }

            if (navMeshObject.editable && GUILayout.Button("Edit Mode: On") || !navMeshObject.editable && GUILayout.Button("Edit Mode: Off"))
            {
                Undo.RecordObject(navMeshObject, "editable");

                navMeshObject.editable = !navMeshObject.editable;

                if (navMeshObject.editable)
                {
                    last          = Tools.current;
                    Tools.current = Tool.None;
                }
                else
                {
                    Tools.current = last;
                }
            }


            GUI.color = Color.white;

            if (GUILayout.Button("Bake NavMesh"))
            {
                GameObjectUtility.SetStaticEditorFlags(navMeshObject.gameObject, StaticEditorFlags.NavigationStatic);
                NavMeshBuilder.BuildNavMesh();
            }

            if (GUILayout.Button("Save NavMeshObject Mesh"))
            {
                string path = "Assets/NavMeshEx/Assets/";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                AssetDatabase.CreateAsset(Instantiate(navMeshObject.mesh), path + navMeshObject.gameObject.name + ".asset");
                AssetDatabase.SaveAssets();
            }
        }
Ejemplo n.º 11
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            NavMeshBuilder.BuildNavMesh();
        }

        if (Input.GetKeyDown(KeyCode.S))
        {
        }
    }
Ejemplo n.º 12
0
 // expensive modafoka
 public void Bake()
 {
     foreach (NavMeshBakeable bakeable in GameObject.FindObjectsOfType <NavMeshBakeable>())
     {
         bakeable.SetStatic(true);
     }
     NavMeshBuilder.BuildNavMesh();
     foreach (NavMeshBakeable bakeable in GameObject.FindObjectsOfType <NavMeshBakeable>())
     {
         bakeable.SetStatic(false);
     }
 }
    protected void generateIA(List <Door> doorList, int w, int h)
    {
        NavMeshBuilder.BuildNavMesh();
        this.doors = doorList;
        Door d = selectDoor();

        d.translateInto(w, h);

        for (int i = 0; i < numIAsCreated; i++)
        {
            Instantiate(prefab, new Vector3(512 * d.y_t, (float)i, 512 * d.x_t), Quaternion.identity);
        }
    }
Ejemplo n.º 14
0
    static void BeginBuildNavigation()
    {
        CopyColToTemp("MapScene");

        GameObject mapScene = GameObject.Find("MapScene") as GameObject;

        if (mapScene != null)
        {
            mapScene.SetActive(false);
        }
        //创建导航网格
        NavMeshBuilder.BuildNavMesh();
        Export();
    }
        //------------------------------------------------------------------------------------------------------------------
        void Update()
        {
            GameObject.Find("PREFAB_CameraMovement").transform.position = this.m_charProxy.transform.position;

            //keep char_proxy at NavigationMesh
            if (GameSystem.HeroControl.LeftMouseClick())
            {
                if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out m_hitPosition, 100))
                {
                    //if (m_hitPosition.collider.gameObject.tag == "NavigationMesh")
                    {
                        NavMeshAgent agent = this.m_charProxy.GetComponent <NavMeshAgent>();
                        agent.destination    = m_hitPosition.point;
                        agent.acceleration   = 1000.0f;
                        agent.angularSpeed   = 1000.0f;
                        agent.speed          = 10.0f;
                        agent.updateRotation = true;

                        Debug.Log("clicked navmesh");
                    }
                }
            }

#if UNITY_EDITOR
            if (Input.GetKeyDown(KeyCode.Space))
            {
                m_frameCount = Time.frameCount;
                Debug.Log("space pressed");

                NavMeshBuilder.ClearAllNavMeshes();
                DestroyDungeon();
                m_rebuildNavmesh = true;
            }

            if (m_frameCount < Time.frameCount && m_rebuildNavmesh)
            {
                CreateRandomDungeon();
                MoveAllMapLinkedToFirstPiecePivot(0, 0);
                ScrambleTileVersions();
                ModifyTilePatterns();
                PopulatePiecesAtDungeon();
                PlaceAgentAtStartPointInNavmesh();

                NavMeshBuilder.BuildNavMesh();
                m_rebuildNavmesh = false;
            }
#endif
        }
Ejemplo n.º 16
0
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        HexGridManager hexManager = (HexGridManager)target;

        if (GUILayout.Button("Rebuild Grid From NavMesh"))
        {
            NavMeshBuilder.BuildNavMesh();
            hexManager.RebuildFromNavMesh();
        }

        if (GUILayout.Button("Report Stats"))
        {
            hexManager.ReportStats();
        }
    }
    static void BuildNaviMesh()
    {
        if (NavMeshBuilder.isRunning)
        {
            Debug.LogWarning("NaviMesh builder is already running! Aborted.");
            return;
        }

        Debug.Log("Start building NaviMesh...");

        NavMeshBuilder.ClearAllNavMeshes();

        NavMeshBuilder.BuildNavMesh();

        Debug.Log("NaviMesh building finished. Saving scene...");

        EditorApplication.SaveScene();
    }
Ejemplo n.º 18
0
    protected void generateIA(List <Door> doorList, int w, int h)
    {
        NavMeshBuilder.BuildNavMesh();

        for (int i = 0; i < numIAsCreated; i++)
        {
            this.doors = doorList;
            Door d = selectDoor();
            d.translateInto(w, h);
            this.doors.Remove(d);
            bunnys.Add((GameObject)Instantiate(prefab, new Vector3(512 * d.y_t, (float)i, 512 * d.x_t), Quaternion.identity));
        }


        foreach (GameObject ia in bunnys)
        {
            ia.GetComponent <NavMeshAgent>().SetDestination(GameObject.Find("Bunny 2.0(Clone)").transform.position);
        }
    }
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        StoreManager store = ( StoreManager )target;

        if (!store.CreateComplete)
        {
            setNavMesh = false;
        }

        if (store.CreateComplete && !setNavMesh)
        {
            GameObjectUtility.SetStaticEditorFlags(store.StoreField.gameObject, StaticEditorFlags.NavigationStatic);

            NavMeshBuilder.BuildNavMesh();

            setNavMesh = true;
        }
    }
    void ToolChain()
    {
        if (OnMapCreated != null)
        {
            OnMapCreated(map, doors);
        }

        NavMeshBuilder.BuildNavMesh();
        //Reciclar para spawners
        if (OnLiveNeeded != null)
        {
            OnLiveNeeded(rooms);
        }

        if (OnItemsNeeded != null)
        {
            OnItemsNeeded(map, zoneIDmark);
        }
    }
Ejemplo n.º 21
0
        /// <summary>
        /// Bakes the Unity NavMesh on created NavMeshObjects.
        /// </summary>
        public void BakeNavMesh()
        {
            //loop over renderers and enable them for the baking process,
            //as otherwise the NavMeshBuilder will ignore them
            List <Renderer> disabledObjects = new List <Renderer>();

            foreach (Renderer item in Object.FindObjectsOfType(typeof(Renderer)))
            {
                if (GameObjectUtility.AreStaticEditorFlagsSet(item.gameObject, StaticEditorFlags.NavigationStatic) && !item.enabled)
                {
                    disabledObjects.Add(item);
                    item.GetComponent <Renderer>().enabled = true;
                }
            }

            //trigger navmesh builder
            NavMeshBuilder.BuildNavMesh();
            //re-enable disabled renderers
            disabledObjects.ForEach(obj => obj.enabled = false);

            ShowNotification("NavMesh successfully built.");
        }
Ejemplo n.º 22
0
    private static void CreateNewMap()
    {
        ClearMaps();
        GameObject map     = Instantiate(Resources.Load("CaveMap")) as GameObject;
        var        caveMap = map.GetComponent <CaveMapController>();

        if (caveMap != null)
        {
            MapGenerator mapGen = new MapGenerator();
            mapGen.GenerateMap(_mapWidth, _mapHeight, _wallsDensity + 40, caveMap);
            NavMeshBuilder.BuildNavMesh();
            if (_addNPC)
            {
                Instantiate(Resources.Load("NPCManager"));
            }
            Selection.activeGameObject = map;
        }
        else
        {
            Debug.LogError("No suitable prefab for CaveMap found.");
        }
    }
Ejemplo n.º 23
0
 private void bake()
 {
     NavMeshBuilder.BuildNavMesh();
 }
Ejemplo n.º 24
0
    private void GenerateNavMesh()
    {
        var map = (TilerMap)target;

        var collectionSize = 1;

        foreach (var cell in map.Cells)
        {
            foreach (var t in cell.Tiles)
            {
                var size = t.Collision.Length;
                if (size > collectionSize)
                {
                    collectionSize = size;
                }
            }
        }

        collectionSize = (int)Mathf.Sqrt(collectionSize);

        foreach (var cell in map.Cells)
        {
            var tiles = cell.Tiles;

            var goTrans = cell.transform.Find("navmesh");

            if (goTrans != null)
            {
                DestroyImmediate(goTrans.gameObject);
            }

            goTrans = new GameObject("navmesh").transform;

            goTrans.parent        = cell.transform;
            goTrans.localPosition = new Vector3();

            var collection = new bool[map.TilesPerCell, map.TilesPerCell][];

            for (var y = 0; y < map.TilesPerCell; y++)
            {
                for (var x = 0; x < map.TilesPerCell; x++)
                {
                    collection[y, x] = tiles[y * map.TilesPerCell + x].Collision;
                }
            }

            var merged = Util.MergeArrays(collection, collectionSize);

            var c = new Combine();
            var r = c.FindRect(merged);

            var size            = r.GetLength(0);
            var sizePerCollider = map.CellSize / size;
            var halfCellSize    = map.CellSize / 2f;

            var offset = sizePerCollider / 2f;

            var p = new Point();

            for (var y = 0; y < size; y++)
            {
                for (var x = 0; x < size; x++)
                {
                    var start = r[y, x];
                    if (start != p)
                    {
                        var xx = (x + x + start.X - 1) / 2f;
                        var yy = (y + y - start.Y + 1) / 2f;

                        var posX = sizePerCollider * xx - (halfCellSize - offset);
                        var posY = sizePerCollider * yy - (halfCellSize - offset);

                        var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
                        go.isStatic         = true;
                        go.transform.parent = goTrans;

                        var goPos = new Vector3();
                        goPos.x = posX;
                        goPos.y = 0;
                        goPos.z = posY;

                        go.transform.localPosition = goPos;
                        go.transform.localScale    = new Vector3(start.X * sizePerCollider, 1, start.Y * sizePerCollider);

                        GameObjectUtility.SetNavMeshLayer(go, 1);
                    }
                }
            }
        }

        NavMeshBuilder.ClearAllNavMeshes();
        NavMeshBuilder.BuildNavMesh();



        foreach (var cell in map.Cells)
        {
            var goTrans = cell.transform.Find("navmesh");
            DestroyImmediate(goTrans.gameObject);
        }
    }
Ejemplo n.º 25
0
    static void BeginBuild()
    {
        GameObject go = GameObject.Find("MapScene") as GameObject;

        if (go == null)
        {
            return;
        }

        //如果renderer没有collider的,不要烘焙
        foreach (Renderer r in go.transform.GetComponentsInChildren <Renderer>())
        {
            Collider c = r.gameObject.GetComponent <Collider>();
            {
                if (c == null)
                {
                    GameObjectUtility.SetStaticEditorFlags(r.gameObject, GameObjectUtility.GetStaticEditorFlags(r.gameObject) & ~StaticEditorFlags.NavigationStatic);
                }
            }
        }

        //每一个Collider都必须要有Renderer
        Collider[] cols = go.transform.GetComponentsInChildren <Collider>();
        //记录改变的render
        List <Renderer> colRenderListRecord = new List <Renderer>();

        foreach (Collider col in cols)
        {
            bool isCanWalk = (ComLayer.IsGroundLayer(col.gameObject.layer));
            //不区分可走不可走,全部障碍都可以走
            isCanWalk = true;
            //要吧renderer打开才能烘焙寻路
            if (col is TerrainCollider)
            {
                Terrain mesh = col.GetComponent <Terrain>();
                if (mesh == null)
                {
                    Debuger.LogError(col.name + " 找不到Terrain");
                    continue;
                }
                Debuger.LogError("碰撞含有Terrain组件,导出的obj后端无法使用");
            }
            else
            {
                Renderer mesh = col.GetComponent <Renderer>();
                if (mesh == null)
                {
                    Debuger.LogError(col.name + " 找不到Renderer");
                    continue;
                }
                if (mesh.enabled == false)
                {
                    colRenderListRecord.Add(mesh);
                }
                mesh.enabled = true;
            }
            GameObjectUtility.SetStaticEditorFlags(col.gameObject, StaticEditorFlags.NavigationStatic);
        }

        //设置stepheight
        SerializedObject   settingsObject = new SerializedObject(NavMeshBuilder.navMeshSettingsObject);
        SerializedProperty agentRadius    = settingsObject.FindProperty("m_BuildSettings.agentClimb");

        agentRadius.floatValue = 0.5f;
        settingsObject.ApplyModifiedProperties();

        NavMeshBuilder.BuildNavMesh();

        //吧render不激活
        foreach (Renderer r in colRenderListRecord)
        {
            r.enabled = false;
        }
    }
Ejemplo n.º 26
0
 void init()
 {
     initGround();
     initWall();
     NavMeshBuilder.BuildNavMesh();
 }
Ejemplo n.º 27
0
    // Update is called once per frame
    void Update()
    {
        if (newMap)
        {
            nRooms = level * 5;

            int x = maxSize / 2, y = maxSize / 2;
            map[x, y] = normalRooms[0]; //Primeira sala

            //Gera a disposição e tipo de salas
            for (int i = 0; i < nRooms + 1; i++)
            {
                int randomPath, newX, newY, randomRoom;

                newX = x;
                newY = y;

                if ((x <= 1 || map[x - 1, y] != null) && (x >= maxSize - 2 || map[x + 1, y] != null))
                {
                    randomPath = 1;                                                                                   //Não pode expandir na horizontal
                }
                else if ((y <= 1 || map[x, y - 1] != null) && (y >= maxSize - 2 || map[x, y + 1] != null))
                {
                    randomPath = 0;                                                                                        //Não pode expandir na vertical
                }
                else
                {
                    randomPath = Random.Range(0, 2);  //Escolhe se expande na vertical ou horizontal
                }
                if (randomPath == 0)
                {
                    if (x <= 1 || map[x - 1, y] != null)
                    {
                        x++;                                  //Não pode criar mais salas à esquerda
                    }
                    else if (x >= maxSize - 2 || map[x + 1, y] != null)
                    {
                        x--;                                                 //Não pode criar mais salas à direita
                    }
                    else
                    {
                        while (newX == x)
                        {
                            newX = Random.Range(x - 1, x + 2); //Pode ir para qualquer um dos lados
                        }
                        x = newX;
                    }
                }
                else
                {
                    if (y <= 1 || map[x, y - 1] != null)
                    {
                        y++;                                  //Não pode criar mais salas em baixo
                    }
                    else if (y >= maxSize - 2 || map[x, y + 1] != null)
                    {
                        y--;                                                 //Não pode criar mais salas em cima
                    }
                    else
                    {
                        while (newY == y)
                        {
                            newY = Random.Range(y - 1, y + 2); //Pode ir para qualquer um dos lados
                        }
                        y = newY;
                    }
                }

                if (i == nRooms)
                {
                    map[x, y] = bossRooms[level - 1];              //Sala do boss
                }
                else
                {
                    randomRoom = Random.Range(0, normalRooms.Length); //Escolhe a sala a ser gerada
                    map[x, y]  = normalRooms[randomRoom];
                }
            }

            //Instancia todas as salas na sua posição respectiva
            for (int i = 0; i < maxSize; i++)
            {
                for (int j = 0; j < maxSize; j++)
                {
                    if (map[i, j] != null)
                    {
                        Room r = Instantiate(map[i, j], new Vector3(i * map[i, j].room.GetComponent <Renderer>().bounds.size.x, -1, j * map[i, j].room.GetComponent <Renderer>().bounds.size.z), Quaternion.identity) as Room;

                        SwitchAllFlameTraps(false, r);

                        map[i, j] = r;
                    }
                }
            }

            currentRoom = map[maxSize / 2, maxSize / 2]; //Atribui a sala actual

            //Posiciona a camara e o jogador na primeira sala
            player.transform.position = new Vector3(maxSize / 2 * map[maxSize / 2, maxSize / 2].room.GetComponent <Renderer>().bounds.size.x, 1, maxSize / 2 * map[maxSize / 2, maxSize / 2].room.GetComponent <Renderer>().bounds.size.z);
            cam.transform.position    = new Vector3(maxSize / 2 * map[maxSize / 2, maxSize / 2].room.GetComponent <Renderer>().bounds.size.x, cam.transform.position.y, maxSize / 2 * map[maxSize / 2, maxSize / 2].room.GetComponent <Renderer>().bounds.size.z - 12);

            NavMeshBuilder.BuildNavMesh();

            newMap  = false; //Evita a criação de mapas a cada update
            newRoom = true;
        }

        //Actualizar a posição da camera conforme a sala
        if (cam.transform.position.x < currentRoom.transform.position.x)
        {
            cam.transform.position += Vector3.right * camSpeed * Time.deltaTime;
        }
        if (cam.transform.position.x > currentRoom.transform.position.x)
        {
            cam.transform.position -= Vector3.right * camSpeed * Time.deltaTime;
        }
        if (cam.transform.position.z < currentRoom.transform.position.z - 12)
        {
            cam.transform.position += Vector3.forward * camSpeed * Time.deltaTime;
        }
        if (cam.transform.position.z > currentRoom.transform.position.z - 12)
        {
            cam.transform.position -= Vector3.forward * camSpeed * Time.deltaTime;
        }

        //Verificar se sala já foi derrotada e abrir portas
        if (currentRoom.clear)
        {
            //Abre porta da esquerda
            if ((int)GetCurrentRoomCoordinates().x - 1 >= 0 && map[(int)GetCurrentRoomCoordinates().x - 1, (int)GetCurrentRoomCoordinates().y] != null)
            {
                map[(int)GetCurrentRoomCoordinates().x - 1, (int)GetCurrentRoomCoordinates().y].OpenDoor(1);
                currentRoom.OpenDoor(0);
            }

            //Abre porta da direita
            if ((int)GetCurrentRoomCoordinates().x + 1 < maxSize && map[(int)GetCurrentRoomCoordinates().x + 1, (int)GetCurrentRoomCoordinates().y] != null)
            {
                map[(int)GetCurrentRoomCoordinates().x + 1, (int)GetCurrentRoomCoordinates().y].OpenDoor(0);
                currentRoom.OpenDoor(1);
            }

            //Abre porta de cima
            if ((int)GetCurrentRoomCoordinates().y + 1 < maxSize && map[(int)GetCurrentRoomCoordinates().x, (int)GetCurrentRoomCoordinates().y + 1] != null)
            {
                map[(int)GetCurrentRoomCoordinates().x, (int)GetCurrentRoomCoordinates().y + 1].OpenDoor(3);
                currentRoom.OpenDoor(2);
            }

            //Abre porta de baixo
            if ((int)GetCurrentRoomCoordinates().y - 1 >= 0 && map[(int)GetCurrentRoomCoordinates().x, (int)GetCurrentRoomCoordinates().y - 1] != null)
            {
                map[(int)GetCurrentRoomCoordinates().x, (int)GetCurrentRoomCoordinates().y - 1].OpenDoor(2);
                currentRoom.OpenDoor(3);
            }

            if (currentRoom.boss)
            {
                //ResetMap(); //Reinicia o mapa
                //level++; //Próximo nível
                //player.GetComponent<Player>().health = player.GetComponent<Player>().startingHealth; //HP do jogador fica a 100%

                Application.LoadLevel("Menu");
            }
        }
        else if (newRoom)
        {
            //Fecha todas as portas
            currentRoom.CloseDoor(0);
            currentRoom.CloseDoor(1);
            currentRoom.CloseDoor(2);
            currentRoom.CloseDoor(3);

            //Activa todos os flame traps
            SwitchAllFlameTraps(true, currentRoom);

            if (currentRoom.AllDoorsClosed())
            {
                //Activa todos os spawners
                foreach (Transform c in currentRoom.transform)
                {
                    if (c.GetComponents <Spawner>().Length > 0)
                    {
                        c.gameObject.SetActive(true);
                    }
                }
                newRoom = false;
            }
        }

        //Verificar em que sala está o jogador
        if (player != null)
        {
            for (int i = 0; i < maxSize; i++)
            {
                for (int j = 0; j < maxSize; j++)
                {
                    if (map[i, j] != null &&
                        player.transform.position.x <map[i, j].transform.position.x + map[i, j].room.GetComponent <Renderer>().bounds.size.x / 2 &&
                                                     player.transform.position.x> map[i, j].transform.position.x - map[i, j].room.GetComponent <Renderer>().bounds.size.x / 2 &&
                        player.transform.position.z <map[i, j].transform.position.z + map[i, j].room.GetComponent <Renderer>().bounds.size.z / 2 &&
                                                     player.transform.position.z> map[i, j].transform.position.z - map[i, j].room.GetComponent <Renderer>().bounds.size.z / 2)
                    {
                        if (currentRoom != map[i, j])
                        {
                            SwitchAllFlameTraps(false, currentRoom);
                            newRoom     = true;
                            currentRoom = map[i, j];
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 28
0
    static void BakeNavMesh(string sceneName)
    {
        GameObject[] _list = null;
        UnityEngine.SceneManagement.Scene s = EditorSceneManager.GetActiveScene();
        if (sceneName.IndexOf("zhandoufuben_") >= 0 || (sceneName == ""))
        {
            if (sceneName != "")
            {
                s = EditorSceneManager.OpenScene(sceneName);
            }
            GameObject[] objs     = s.GetRootGameObjects();
            bool         bFindObj = false;
            for (int i = 0; i < objs.Length; i++)
            {
                if (objs[i].name == "Scene")
                {
                    Transform area = objs[i].transform.Find("World/WalkableArea");//显示寻路层,并设为static
                    if (area != null)
                    {
                        bFindObj = true;
                        SetAllChildrenStatic(objs[i], false);
                        SetAllChildrenStatic(area.gameObject, true);
                        SetAllChildrenVisible(area.gameObject, true);
                    }
                    else
                    {
                        Utils.LogSys.LogError("Not Found WalkableArea: " + sceneName);
                    }
                    _list = GameObject.FindGameObjectsWithTag("WalkObstacle");
                    if (_list != null && _list.Length > 0)
                    {
                        for (int k = 0; k < _list.Length; k++)
                        {
                            if (!_dic_is_active.ContainsKey(_list[i]))
                            {
                                _dic_is_active.Add(_list[i], _list[i].activeSelf);
                            }
                            if (!_dic_is_static.ContainsKey(_list[i]))
                            {
                                _dic_is_static.Add(_list[i], _list[i].isStatic);
                            }
                            _list[i].SetActive(true);
                            _list[i].isStatic = true;
                        }
                    }
                    break;
                }
            }
            if (!bFindObj)
            {
                if (sceneName == "")
                {
                    Utils.LogSys.LogError("Not Found Scene Node: " + s.name);
                }
                else
                {
                    Utils.LogSys.LogError("Not Found Scene Node: " + sceneName);
                }
            }
            else
            {
                // Rebake navmesh data
                NavMeshBuilder.BuildNavMesh();
            }


            foreach (KeyValuePair <GameObject, bool> item in _dic_is_active)
            {
                item.Key.SetActive(item.Value);
            }
            foreach (KeyValuePair <GameObject, bool> item in _dic_is_static)
            {
                item.Key.isStatic = item.Value;
            }
            EditorSceneManager.SaveScene(s);
            _dic_is_active.Clear();
            _dic_is_static.Clear();
        }
    }
Ejemplo n.º 29
0
    void GenerateMap()
    {
        map            = new int[_width, _height];
        _randomOffset += UnityEngine.Random.Range(0, 1000);
        if (_useRandomSeed)
        {
            _randomOffset = UnityEngine.Random.Range(_randomOffset, _randomOffset + 100);
            _seed         = (_randomOffset + Time.time).ToString();
        }
        else
        {
            _seed = "Sillyatom";
        }

        System.Random pseudoRandom = new System.Random(_seed.GetHashCode());

        for (int x = 0; x < _width; x++)
        {
            for (int y = 0; y < _height; y++)
            {
                if (x == 0 || x == _width - 1 || y == 0 || y == _height - 1)
                {
                    map[x, y] = 1;
                }
                else
                {
                    map[x, y] = pseudoRandom.Next(0, 100) < _randomPercentage ? 1 : 0;
                }
            }
        }

        SmoothMap();

        ProcessMap();

        int borderSize = 1;

        borderedMap = new int[_width + borderSize * 2, _height + borderSize * 2];

        for (int x = 0; x < borderedMap.GetLength(0); x++)
        {
            for (int y = 0; y < borderedMap.GetLength(1); y++)
            {
                if (x >= borderSize && x < _width + borderSize && y >= borderSize && y < _height + borderSize)
                {
                    borderedMap[x, y] = map[x - borderSize, y - borderSize];
                }
                else
                {
                    borderedMap[x, y] = 1;
                }
            }
        }

        GetComponent <MeshGenerator>().GenerateMesh(borderedMap, _gridSize);

        //for testing
        int[,] walkableMap = new int[borderedMap.GetLength(0), borderedMap.GetLength(1)];

        for (int x = 0; x < borderedMap.GetLength(0); x++)
        {
            for (int y = 0; y < borderedMap.GetLength(1); y++)
            {
                walkableMap[x, y] = (borderedMap[x, y] == 1) ? 0 : 1;
            }
        }
        GetComponent <MeshGenerator>().GenerateNavMesh(walkableMap, _gridSize);

        NavMeshBuilder.BuildNavMesh();

        Events.instance.Raise(new GameEvent(GameEvent.BUILD_NAVMESH_COMPLETE, borderedMap.GetLength(0), borderedMap.GetLength(1), _gridSize));
    }
Ejemplo n.º 30
0
        public static void GenerateMapFromTMXFile()
        {
            var currentScene = SceneManager.GetActiveScene();

            var mapData     = ReadTMXFileForMapData(GetMapFilename(currentScene.name));
            var worldParent = new GameObject("_World");

            var index       = 0;
            var tilesetData = mapData.tilesetData;

            for (var i = 0; i < mapData.height; i++)
            {
                for (var j = 0; j < mapData.width; j++)
                {
                    var id = mapData.data[i][j];
                    var tilesetDataIndex = -1;

                    tilesetDataIndex = tilesetData.FindIndex(obj => id >= obj.firstgid && id <= (obj.firstgid + obj.tilecount - 1));

                    if (tilesetDataIndex == -1)
                    {
                        continue;
                    }

                    var isRoadPrefab = false;   //required for nav mesh editor flag
                    id -= tilesetData[tilesetDataIndex].firstgid - 1;
                    var prefix   = tilesetData[tilesetDataIndex].prefix;
                    var filename = prefix + id.ToString();
                    var scale    = new Vector3(); //kenney pack 1 has different scaling compared to kenney pack 2
                    var filepath = GetFilepathForWorld(@"Prefabs/TowerDefense", filename, ref isRoadPrefab, ref scale);

                    if (filepath.Equals(string.Empty))
                    {
                        continue;
                    }

                    var asset = Resources.Load(filepath) as GameObject;
                    if (asset == null)
                    {
                        continue;
                    }

                    asset.transform.localScale = scale;

                    var tile = Instantiate(asset, new Vector3(j * Constants.TILE_SIZE.x, Constants.TILE_SIZE.x, -i * Constants.TILE_SIZE.y), Quaternion.identity) as GameObject;
                    tile.transform.parent = worldParent.transform;
                    tile.name             = "go_" + index + asset.name;

                    GameObjectUtility.SetStaticEditorFlags(tile, StaticEditorFlags.BatchingStatic);

                    var children = tile.GetComponentsInChildren <Transform>();
                    for (var k = 0; k < children.Length; k++)
                    {
                        GameObjectUtility.SetStaticEditorFlags(children[k].gameObject,
                                                               isRoadPrefab ? StaticEditorFlags.NavigationStatic | StaticEditorFlags.BatchingStatic : StaticEditorFlags.BatchingStatic);
                    }

                    index++;
                }
            }

            NavMeshBuilder.ClearAllNavMeshes();
            NavMeshBuilder.BuildNavMesh();

            UnityEditor.SceneManagement.EditorSceneManager.SaveScene(currentScene);
        }