public static void ExportNavMesh()
        {
            Debug.Log("exporting NavMesh...");

            //Create NavMesh Obj file.
            NavMeshTriangulation tris = UnityEngine.AI.NavMesh.CalculateTriangulation();

            int[]     areas   = tris.areas;
            Vector3[] verts   = tris.vertices;
            int[]     indices = tris.indices;

            if (File.Exists(EditorPaths.exportedRawNavMeshPath))
            {
                File.Delete(EditorPaths.exportedRawNavMeshPath);
            }

            StreamWriter sw = new StreamWriter(EditorPaths.exportedRawNavMeshPath);

            for (int i = 0; i < verts.Length; i++)
            {
                sw.WriteLine("v " + verts[i].x + " " + verts[i].y + " " + verts[i].z);
            }

            sw.WriteLine("g obj ");

            for (int i = 0; i < indices.Length;)
            {
                sw.WriteLine("f " + (indices[i + 0] + 1) + " " + (indices[i + 1] + 1) + " " + (indices[i + 2] + 1));
                i = i + 3;
            }
            sw.Flush();
            sw.Close();
            sw.Dispose();
            Debug.Log("NavMesh exported.");
        }
Exemple #2
0
    Vector3 GetRandomLocation()
    {
        NavMeshTriangulation navMeshData = NavMesh.CalculateTriangulation();

        int maxIndices = navMeshData.indices.Length - 3;
        // Pick the first indice of a random triangle in the nav mesh
        int firstVertexSelected  = Random.Range(0, maxIndices);
        int secondVertexSelected = Random.Range(0, maxIndices);
        //Spawn on Verticies
        Vector3 point = navMeshData.vertices[navMeshData.indices[firstVertexSelected]];

        Vector3 firstVertexPosition  = navMeshData.vertices[navMeshData.indices[firstVertexSelected]];
        Vector3 secondVertexPosition = navMeshData.vertices[navMeshData.indices[secondVertexSelected]];

        //Eliminate points that share a similar X or Z position to stop spawining in square grid line formations
        if ((int)firstVertexPosition.x == (int)secondVertexPosition.x ||
            (int)firstVertexPosition.z == (int)secondVertexPosition.z
            )
        {
            point = GetRandomLocation(); //Re-Roll a position - I'm not happy with this recursion it could be better
        }
        else
        {
            // Select a random point on it
            point = Vector3.Lerp(
                firstVertexPosition,
                secondVertexPosition,      //[t + 1]],
                Random.Range(0.05f, 0.95f) // Not using Random.value as clumps form around Verticies
                );
        }
        //Vector3.Lerp(point, navMeshData.vertices[navMeshData.indices[t + 2]], Random.value); //Made Obsolete

        return(point);
    }
Exemple #3
0
    public static void FilterDuplicate(NavMeshTriangulation nt, out List <Vector3> vertices, out List <int> indices, out List <int> layers)
    {
        vertices = new List <Vector3>(nt.vertices);
        indices  = new List <int>(nt.indices);
        layers   = new List <int>(nt.layers);
        int index = 0;

        while (index < vertices.Count)
        {
            for (int i = vertices.Count - 1; i > index; i--)
            {
                if (Vector3.Distance(vertices[i], vertices[index]) < 0.001f)
                {
                    vertices.RemoveAt(i);
                    for (int s = indices.Count - 1; s >= 0; s--)
                    {
                        if (indices[s] == i)
                        {
                            indices[s] = index;
                        }
                        else if (indices[s] > i)
                        {
                            indices[s] -= 1;
                        }
                    }
                }
            }
            index += 1;
        }
    }
Exemple #4
0
    /*
     * 床面推定が完了した時に呼ばれるメソッド。推定された床面は3Dオブジェクト(SurfacePlane)として取得できる(ここでは、SurfacePlaneとして取得しなくても良いため、GameObjectとして検索している)。
     * タグ"Plane"がついたSurfacePlaneが推定された床面であるが、それに対しNavMeshSourceTagという要素を付加することで後にNavMeshによる歩行可能エリアの計算がその面に対して可能になる。
     */
    private void SurfaceMeshesToPlanes_MakePlanesComplete(object source, System.EventArgs args)
    {
        RemoveSurfaceVertices.Instance.RemoveSurfaceVerticesWithinBounds(SurfaceMeshesToPlanes.Instance.ActivePlanes);
        //SpatialMappingManager.Instance.DrawVisualMeshes = false;
        SpatialMappingManager.Instance.StartObserver();
        var planes = GameObject.FindGameObjectsWithTag("Plane");

        if (planes.Length != 0)
        {
            foreach (GameObject item in planes)
            {
                item.gameObject.AddComponent <NavMeshSourceTag> ();
            }
            makedPlane = true;
            //NavMeshの三角形集合取得
            NavMeshTriangulation triangles = NavMesh.CalculateTriangulation();
            Vector3[]            v         = triangles.vertices;
            for (int i = 0; i < v.Length; i++)
            {
                mkRoute.huNav.log.writeMessage_area("area" + areaNum + "," + v[i].x + "," + v[i].z);
            }
            areaNum++;
        }
        else
        {
            makedPlane = false;
        }
    }
Exemple #5
0
    static void Export()
    {
        Debug.Log("ExportNavMesh");

        NavMeshTriangulation tmpNavMeshTriangulation = NavMesh.CalculateTriangulation();

        //新建文件
        string       tmpPath         = Application.dataPath + "/" + SceneManager.GetActiveScene().name + ".obj";
        StreamWriter tmpStreamWriter = new StreamWriter(tmpPath);

        //顶点
        for (int i = 0; i < tmpNavMeshTriangulation.vertices.Length; i++)
        {
            tmpStreamWriter.WriteLine("v  " + tmpNavMeshTriangulation.vertices[i].x + " " + tmpNavMeshTriangulation.vertices[i].y + " " + tmpNavMeshTriangulation.vertices[i].z);
        }

        tmpStreamWriter.WriteLine("g pPlane1");

        //索引
        for (int i = 0; i < tmpNavMeshTriangulation.indices.Length;)
        {
            tmpStreamWriter.WriteLine("f " + (tmpNavMeshTriangulation.indices[i] + 1) + " " + (tmpNavMeshTriangulation.indices[i + 1] + 1) + " " + (tmpNavMeshTriangulation.indices[i + 2] + 1));
            i = i + 3;
        }

        tmpStreamWriter.Flush();
        tmpStreamWriter.Close();

        Debug.Log("ExportNavMesh Success");
    }
Exemple #6
0
    /// \brief Converts a NavMesh (or a NavMesh area) into a standard Unity mesh.  This is later used
    ///        to render the mesh on-screen using Unity's standard rendering tools.
    ///
    /// \param navMesh Precalculated Nav Mesh Triangulation
    /// \param vert_size size of vertex array
    /// \param tri_size size of triangle array
    private static Mesh ConvertNavmeshToMesh(NavMeshTriangulation navMesh, int vert_size, int tri_size)
    {
        Mesh ret = new Mesh();

        if (vert_size >= 65535)
        {
            Debug.LogError("Playable NavMesh too big (vertex count >= 65535)!  Limit the size of the playable area using" +
                           "Area Masks.  For now no preview mesh will render.");
            return(ret);
        }

        Vector3[] vertices = new Vector3[vert_size];
        for (int x = 0; x < vertices.Length; x++)
        {
            // Note: Unity navmesh is offset 0.05m from the ground.  This pushes it down to 0
            vertices[x] = navMesh.vertices[x];
        }

        int[] triangles = new int[tri_size * 3];
        for (int x = 0; x < triangles.Length; x++)
        {
            triangles[x] = navMesh.indices[x];
        }

        ret.name      = "Navmesh";
        ret.vertices  = vertices;
        ret.triangles = triangles;

        RemoveMeshDuplicates(ret);

        ret.RecalculateNormals();
        ret.RecalculateBounds();

        return(ret);
    }
Exemple #7
0
    /// \brief Converts a NavMesh (or a NavMesh area) into a standard Unity mesh.  This is later used
    ///        to render the mesh on-screen using Unity's standard rendering tools.
    ///
    /// \param navMesh Precalculated Nav Mesh Triangulation
    /// \param area area to consider in calculation
    private static Mesh ConvertNavmeshToMesh(NavMeshTriangulation navMesh, int area)
    {
        Mesh ret = new Mesh();

        Vector3[] vertices = new Vector3[navMesh.vertices.Length];
        for (int x = 0; x < vertices.Length; x++)
        {
            vertices[x] = navMesh.vertices[x];
        }

        int[] triangles = new int[navMesh.indices.Length];
        for (int x = 0; x < triangles.Length; x++)
        {
            triangles[x] = navMesh.indices[x];
        }

        ret.name      = "Navmesh";
        ret.vertices  = vertices;
        ret.triangles = triangles;

        RemoveMeshDuplicates(ret);

        ret.RecalculateNormals();
        ret.RecalculateBounds();

        return(ret);
    }
    public const int MAX_WALL = 7; //can change this to create a geant map


    // Start is called before the first frame update
    void Start()
    {
        float begin = Time.realtimeSinceStartup;

        this.seed = Mathf.FloorToInt(Random.value * int.MaxValue);
        Random.InitState(seed);

        MapGeneration();
        surface.BuildNavMesh();

        surface.AddData(); //Add the surface to the singleton Nav Mesh


        NavMeshTriangulation navMeshTriangulation = NavMesh.CalculateTriangulation();

        DebugDisplayTriangle(navMeshTriangulation);


        MapGraph mapGraph = GenerateGraph(navMeshTriangulation);

        mapGraph.DeugDrawGrahp();

        Debug.Log("Generation took " + (Time.realtimeSinceStartup - begin) + " seconds");
        GenerateLights(mapGraph);

        TemporaryPlayerGeneration(mapGraph);

        surface.RemoveData(); //Remove the surface to the singleton NavMesh

        surface_enemy.BuildNavMesh();
        GenerateEnemies(5, mapGraph);


        gameObject.BroadcastMessage("StartTheGame");
    }
Exemple #9
0
    // Update is called once per frame
    void Update()
    {
        // made it to destination
        if (Vector3.Distance(transform.position, navMeshAgent.destination) < 1f)
        {
            NavMeshTriangulation data = NavMesh.CalculateTriangulation();
            Vector3 vertex            = data.vertices[Random.Range(0, data.vertices.Length)];
            navMeshAgent.destination = vertex;
        }

        // collision with player
        foreach (PlayerController p in players)
        {
            if (Vector3.Distance(transform.position, p.transform.position) <= range)
            {
                colorCaster.playerTag = p.PlayerTag;

                // Change Material
                if (colorMaterials[(int)p.PlayerTag])
                {
                    GetComponentInChildren <Renderer>().material = colorMaterials[(int)p.PlayerTag];
                }
            }
        }
    }
Exemple #10
0
    private void drawNavMesh()
    {
        NavMeshTriangulation nt = NavMesh.CalculateTriangulation();

        m.vertices  = nt.vertices;
        m.triangles = nt.indices;
    }
    void ShowNavMesh()
    {
        triangles = NavMesh.CalculateTriangulation();
        mesh      = new Mesh();

        vertices       = triangles.vertices;
        indices        = triangles.indices;;
        mesh.vertices  = vertices;
        mesh.triangles = indices;
        indicesCount   = indices.Length;

        if (meshShowObj)
        {
            Mesh mesh2 = meshShowObj.GetComponent <MeshFilter>().mesh;
            mesh2.Clear();
            mesh2.vertices  = vertices;
            mesh2.triangles = indices;
            //mesh.Optimize();
            mesh2.RecalculateNormals();
            //if (meshShowObj.GetComponent<MeshCollider>() == null)
            //{
            //    meshShowObj.AddComponent<MeshCollider>();
            //}

            //Collider collider = meshShowObj.GetComponent<Collider>();
            //var p=collider.ClosestPoint(targetPos);
            //NavMeshHelper.CreatePoint(p, "MeshCollider", 0.5f, Color.yellow);
        }

        //ShowVertices();
        ShowNavMeshPoints();
    }
Exemple #12
0
    // Start is called before the first frame update

    void Start()
    {
        _navMeshAgent = this.GetComponent <NavMeshAgent>();
        _animator     = this.GetComponent <Animator>();
        ListLines     = new GameObject();
        ListLines.transform.parent = this.transform.parent;
        ListLines.name             = "ListLines";
        path = GetComponentInParent <MeshFilter>().mesh;
        path.Clear();
        astar           = new AStar();
        path.name       = "ola";
        Graph           = astar.Graph;
        triangulization = astar.triangulation;
        astar.setOrigin(transform.position);
        astar.setDestination(_destination.position);
        MarioHasDestination = false;
        Lastmovement        = false;
        FirsTriangle        = true;
        stopped             = false;
        NextPoint           = new Vector3();
        Speed           = 10;
        MaxSpeed        = 10;
        Acceleration    = 10;
        Deceleration    = 10;
        currentTriangle = -1;
        //parent = GetComponentInParent<GameObject>();
        script = GetComponentInParent <GraphData>();
        //paintPath(trianglePath, Color.red);
        //paintTriangleNeigh(26, Color.black, Color.red);
    }
        static NavEdge TriangleToEdge(NavMeshTriangulation tri, int start, int end)
        {
            var v1 = tri.vertices[tri.indices[start]];
            var v2 = tri.vertices[tri.indices[end]];

            return(new NavEdge(v1, v2));
        }
Exemple #14
0
    static string MeshToString(NavMeshTriangulation mesh, bool isBlock)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append(isBlock ? "\"blockTriangles\":[" : "\"pathTriangles\":[");
        for (int i = 0; i < mesh.indices.Length; i++)
        {
            sb.Append(mesh.indices[i]).Append(",");
        }
        sb.Length--;
        sb.Append("],");

        sb.Append(isBlock ? "\"blockVertices\":[" : "\"pathVertices\":[");
        for (int i = 0; i < mesh.vertices.Length; i++)
        {
            Vector3 v = mesh.vertices[i];
            if (!isBlock && v.y < 1)
            {
                Debug.LogWarning("寻路mesh坐标小于1" + v.y);
            }
            sb.Append("{\"x\":").Append(v.x).Append(",\"y\":").Append(isBlock ? 0 : v.y).Append(",\"z\":").Append(v.z).Append("},");
        }
        sb.Length--;
        sb.Append("]");
        return(sb.ToString());
    }
Exemple #15
0
    public void Awake()
    {
        instance = this;
        NavMeshTriangulation navMeshTriangulation = NavMesh.CalculateTriangulation();

        navMesh           = new Mesh();
        navMesh.vertices  = navMeshTriangulation.vertices;
        navMesh.triangles = navMeshTriangulation.indices;
        int num = navMeshTriangulation.indices.Length / 3;

        navWeights = new float[num];
        float num2 = 0f;

        for (int i = 0; i < num; i++)
        {
            Vector3 a          = navMesh.vertices[navMesh.triangles[i * 3]];
            Vector3 vector     = navMesh.vertices[navMesh.triangles[i * 3 + 1]];
            Vector3 b          = navMesh.vertices[navMesh.triangles[i * 3 + 2]];
            float   magnitude  = (a - vector).magnitude;
            float   magnitude2 = (a - b).magnitude;
            float   magnitude3 = (vector - b).magnitude;
            float   num3       = (magnitude + magnitude2 + magnitude3) * 0.5f;
            float   num4       = Mathf.Sqrt(num3 * (num3 - magnitude) * (num3 - magnitude2) * (num3 - magnitude3));
            navWeights[i] = num4;
            num2         += num4;
        }
        for (int i = 0; i < num; i++)
        {
            navWeights[i] /= num2;
        }
    }
Exemple #16
0
    //测试用
    void ExportNavMeshTest()
    {
        NavMeshTriangulation triangulatedNavMesh = NavMesh.CalculateTriangulation();

        Mesh mesh = new Mesh();

        mesh.name      = "_NavMesh";
        mesh.vertices  = triangulatedNavMesh.vertices;
        mesh.triangles = triangulatedNavMesh.indices;

        GameObject test = new GameObject("TestMesh");
        MeshFilter mf   = test.AddComponent <MeshFilter>();

        test.AddComponent <MeshRenderer>();
        mf.mesh = mesh;



        for (int i = 0; i < mesh.vertices.Length; ++i)
        {
            GameObject sp = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            sp.transform.position = test.transform.TransformPoint(mesh.vertices[i]);
            sp.transform.parent   = test.transform;
        }
    }
    public Vector3 GetRandomPointOnNavMesh()
    {
        Vector3 randomPoint;

        do
        {
            NavMeshTriangulation navMeshTriangulation = NavMesh.CalculateTriangulation();

            int randomIndex = Random.Range(0, navMeshTriangulation.indices.Length - 3);

            randomPoint = Vector3.Lerp(navMeshTriangulation.vertices[navMeshTriangulation.indices[randomIndex]],
                                       navMeshTriangulation.vertices[navMeshTriangulation.indices[randomIndex + 1]], Random.value);

            Vector3.Lerp(randomPoint, navMeshTriangulation.vertices[navMeshTriangulation.indices[randomIndex + 2]],
                         Random.value);
        } while (randomPoint.y > 1);

        /* Use this to debug the destination point with a cube
         * GameObject primitive = GameObject.CreatePrimitive(PrimitiveType.Cube);
         *
         * primitive.GetComponent<Renderer>().material.color = Color.red;
         *
         * if (primitive != null)
         * primitive.transform.position = randomPoint;
         */

        return(randomPoint);
    }
Exemple #18
0
    //导出NavMesh的数据
    void ExportNavMesh()
    {
        NavMeshTriangulation triangulatedNavMesh = NavMesh.CalculateTriangulation();

        Mesh mesh = new Mesh();

        mesh.name      = "_NavMesh";
        mesh.vertices  = triangulatedNavMesh.vertices;
        mesh.triangles = triangulatedNavMesh.indices;

        string baseName = "navmesh_" + SceneManager.GetActiveScene().name;
        string fileName = Application.dataPath + "/navmesh/" + baseName + ".obj";
        string txtName  = Application.dataPath + "/navmesh/" + baseName + ".txt";

        NavMeshToMeshObj(mesh, fileName);
        NavMeshToBinaryFile(mesh, txtName);
        AssetDatabase.Refresh();

        /*
         * string assetName = fileName.Replace(Application.dataPath, "Assets");
         * GameObject navMesh = Instantiate(AssetDatabase.LoadAssetAtPath<GameObject>(assetName));
         * navMesh.name = baseName;
         * MeshObjToBinaryFile(navMesh);
         */
        Debug.Log("导出完成:" + baseName);
        AssetDatabase.Refresh();
    }
        static void Export()
        {
            Debug.Log("NavmMesh Export Start");
            NavMeshTriangulation navMeshTriangulation = NavMesh.CalculateTriangulation();

            //文件路径 路径文件夹不存在会报错
            string path = Application.dataPath + "/Scripts/Obj/" + SceneManager.GetActiveScene().name + ".obj";

            //新建文件
            StreamWriter streamWriter = new StreamWriter(path);

            //顶点
            for (int i = 0; i < navMeshTriangulation.vertices.Length; i++)
            {
                streamWriter.WriteLine("v " + navMeshTriangulation.vertices[i].x + " " + navMeshTriangulation.vertices[i].y + " " + navMeshTriangulation.vertices[i].z);
            }

            streamWriter.WriteLine("g pPlane1");

            //索引
            for (int i = 0; i < navMeshTriangulation.indices.Length; i++)
            {
                streamWriter.WriteLine("f " + (navMeshTriangulation.indices[i] + 1) + " " + (navMeshTriangulation.indices[i + 1] + 1) + " " + (navMeshTriangulation.indices[i + 2] + 1));
                i = i + 3;
            }

            streamWriter.Flush();
            streamWriter.Close();

            AssetDatabase.Refresh();

            Debug.Log("NavMesh Export Success");
        }
Exemple #20
0
    private Vector3 GetRandomGameBoardLocation()
    {
        NavMeshTriangulation navMeshData = NavMesh.CalculateTriangulation();

        int maxIndices = navMeshData.indices.Length - 3;

        // pick the first indice of a random triangle in the nav mesh
        int firstVertexSelected  = Random.Range(0, maxIndices);
        int secondVertexSelected = Random.Range(0, maxIndices);

        // spawn on verticies
        Vector3 point = navMeshData.vertices[navMeshData.indices[firstVertexSelected]];

        Vector3 firstVertexPosition  = navMeshData.vertices[navMeshData.indices[firstVertexSelected]];
        Vector3 secondVertexPosition = navMeshData.vertices[navMeshData.indices[secondVertexSelected]];

        // eliminate points that share a similar X or Z position to stop spawining in square grid line formations
        if ((int)firstVertexPosition.x == (int)secondVertexPosition.x || (int)firstVertexPosition.z == (int)secondVertexPosition.z)
        {
            point = GetRandomGameBoardLocation(); // re-roll a position - I'm not happy with this recursion it could be better
        }
        else
        {
            // select a random point on it
            point = Vector3.Lerp(firstVertexPosition, secondVertexPosition, UnityEngine.Random.Range(0.05f, 0.95f));
        }

        return(point);
    }
    // Use this for initialization
    void Start()
    {
        UnityEngine.Random.InitState(0);
        verticalOffsetFinal  = Vector3.up * VerticalOffset;
        CellList             = new SortedCellList();
        VoronoiNeighborLines = new List <LineRenderer>();
        /// Cycling through all child objects, finding OffMeshLinks
        /// Hope is to connect our Cells together via the OffMeshLinks
        //foreach (Transform child in transform)
        //{
        //	OffMeshLink offMeshLink = child.GetComponent<OffMeshLink>();
        //	if (offMeshLink && offMeshLink.enabled)
        //	{
        //		NavMesh.areas
        //		offMeshLink.area
        //	}
        //}

        // Get all NavMesh information
        NavMeshTriangulation tris = NavMesh.CalculateTriangulation();

        // Spawn vertex prefabs at the vertices of the NavMesh
        foreach (Vector3 vert in tris.vertices)
        {
            Instantiate(NavMeshVertPrefab, vert + verticalOffsetFinal, transform.rotation);
        }

        // Using the indicies of the NavMesh, create Triangles and call PoissonDiscDistribution with it to create
        // Voronoi regions
        for (int index = 0; index < tris.indices.Length; index += 3)
        {
            Triangle tri = new Triangle(
                tris.vertices[tris.indices[index + 0]],
                tris.vertices[tris.indices[index + 1]],
                tris.vertices[tris.indices[index + 2]],
                PoissonDotPrefab, LinePrefab, LineWidth
                );
            NavMeshTris.Add(tri);
            PoissonDiscDistribution(tri, PoissonTolerance);
        }

        for (int i = 0; i < CellList.GetCount(); ++i)
        {
            GetNeighbors(CellList.GetCell(i));
        }
        CellList.RaiseCells(verticalOffsetFinal);
        CellList.AssignIndices();
        CellList.FindWallInfluence(GameObject.FindGameObjectsWithTag("Wall"));
        CellList.FindVisibilityInfluence(NavMeshTris);
        InfluenceMapModeText.GetComponent <ModeUI>().ModeChange(Mode);

        if (Mode == InfluenceMode.OpennessClosestWall)
        {
            CellList.ApplyWallInfluences();
        }
        else if (Mode == InfluenceMode.VisibleToSpot)
        {
            CellList.ApplyVisibilityInfluences();
        }
    }
Exemple #22
0
        public static Vector3 GetRandomLocation()
        {
            while (true)
            {
                NavMeshTriangulation navMeshData = NavMesh.CalculateTriangulation();

                int maxIndices = navMeshData.indices.Length - 3;

                int firstVertexSelected  = Random.Range(0, maxIndices);
                int secondVertexSelected = Random.Range(0, maxIndices);

                Vector3 point;

                Vector3 firstVertexPosition  = navMeshData.vertices[navMeshData.indices[firstVertexSelected]];
                Vector3 secondVertexPosition = navMeshData.vertices[navMeshData.indices[secondVertexSelected]];

                if ((int)firstVertexPosition.x == (int)secondVertexPosition.x || (int)firstVertexPosition.z == (int)secondVertexPosition.z)
                {
                    continue;
                }

                point = Vector3.Lerp(firstVertexPosition, secondVertexPosition,
                                     Random.Range(0.0f, 1f));

                if (NavMesh.SamplePosition(point, out var hit, 2.0f, NavMesh.AllAreas))
                {
                    return(hit.position);
                }
            }
        }
Exemple #23
0
 static void MeshToObjFile(NavMeshTriangulation tgn, NavMeshBuildSettings settings, string filename)
 {
     using (StreamWriter sw = new StreamWriter(filename))
     {
         sw.Write(MeshToObjString(tgn, settings));
     }
 }
Exemple #24
0
    // Use this for initialization
    void Start()
    {
        unityPath = new NavMeshPath();

        MeshFilter meshFilter = this.gameObject.AddComponent <MeshFilter>();

        NavMeshTriangulation triangulatedNavMesh = NavMesh.CalculateTriangulation();

        debugNavMeshVertices.AddRange(triangulatedNavMesh.vertices);
        debugNavMeshIndices.AddRange(triangulatedNavMesh.indices);

        //weld vertices
        for (int i = 0; i < triangulatedNavMesh.indices.Length; i += 3)
        {
            for (int j = 0; j < 3; j++)
            {
                int     vertexIndex = triangulatedNavMesh.indices[i + j];
                Vector3 v           = triangulatedNavMesh.vertices[vertexIndex];
                int     index       = FindIndex(v);
                if (index == -1)
                {
                    vertices.Add(v);
                    index = vertices.Count - 1;
                }
                triangles.Add(index);
            }
        }

        this.ExportNavMesh();

        TNavMesh.Init("G:/navmesh.txt");
    }
Exemple #25
0
        //      ————————————————
        // 版权声明:本文为CSDN博主「_Captain」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
        // 原文链接:https://blog.csdn.net/huutu/article/details/52672505

        private static void WriteUnityObjFile()
        {
            var          path            = outputClientFolder + SceneManager.GetActiveScene().name + "_internal.obj";
            StreamWriter tmpStreamWriter = new StreamWriter(path);

            NavMeshTriangulation tmpNavMeshTriangulation = UnityEngine.AI.NavMesh.CalculateTriangulation();

            //顶点
            for (int i = 0; i < tmpNavMeshTriangulation.vertices.Length; i++)
            {
                tmpStreamWriter.WriteLine("v  " + tmpNavMeshTriangulation.vertices[i].x + " " + tmpNavMeshTriangulation.vertices[i].y + " " +
                                          tmpNavMeshTriangulation.vertices[i].z);
            }

            tmpStreamWriter.WriteLine("g pPlane1");

            //索引
            for (int i = 0; i < tmpNavMeshTriangulation.indices.Length;)
            {
                tmpStreamWriter.WriteLine("f " + (tmpNavMeshTriangulation.indices[i] + 1) + " " + (tmpNavMeshTriangulation.indices[i + 1] + 1) + " " +
                                          (tmpNavMeshTriangulation.indices[i + 2] + 1));
                i = i + 3;
            }

            tmpStreamWriter.Flush();
            tmpStreamWriter.Close();

            AssetDatabase.Refresh();
        }
    // Use this for initialization
    void Awake()
    {
        navMeshAgent = GetComponent <NavMeshAgent>();
        if (startObject != null)
        {
            startPosition = startObject.transform.position;
            startRotation = startObject.transform.rotation;
        }
        if (ghostCageObject != null)
        {
            ghostCagePosition = ghostCageObject.transform.position;
        }

        isActive = false;
        isScared = false;
        isEaten  = false;
        MeshFilter meshFilter = GetComponent <MeshFilter>();

        if (meshFilter != null)
        {
            defaultMesh = meshFilter.mesh;
        }
        objectRenderer                  = GetComponent <Renderer>();
        navMeshTriangulation            = NavMesh.CalculateTriangulation();
        navMeshVertices                 = navMeshTriangulation.vertices;
        waitToChoosePoint               = new WaitForSeconds(choosePointIntervalWhenScared);
        waitToBlinkWhenEnergizedNearEnd = new WaitForSeconds(blinkIntervalWhenEnergizedNearEnd);
        currentMaterialIndex            = 0;
    }
Exemple #27
0
    private void startbuildingMode()
    {
        buildingMode = true;
        rotationbar.SetActive(true);
        clickDetector.clearPopUps();
        GameObject.Find("Terrain").GetComponent <Scene_Controller>().buildButton.SetActive(true);
        print("reset override cost");
        overrideCost = null;

        NavMeshTriangulation triangulation = NavMesh.CalculateTriangulation();

        GameObject meshBuilder = GameObject.Find("NavController");

        meshBuilder.GetComponent <MeshRenderer>().enabled = true;
        //meshBuilder.AddComponent<MeshFilter>();
        //meshBuilder.AddComponent<MeshRenderer>();
        Mesh mesh = meshBuilder.GetComponent <MeshFilter>().mesh;

        mesh.Clear();

        mesh.vertices  = triangulation.vertices;
        mesh.triangles = triangulation.indices;
        Vector2[] uvs = new Vector2[triangulation.vertices.Length];

        for (int i = 0; i < uvs.Length; i++)
        {
            uvs[i] = new Vector2(triangulation.vertices[i].x, triangulation.vertices[i].z);
        }
        mesh.uv = uvs;
        meshBuilder.GetComponent <MeshRenderer>().enabled    = true;
        meshBuilder.GetComponent <MeshCollider>().sharedMesh = mesh;

        Time.timeScale = 0.1f;
    }
Exemple #28
0
    public void UpdateNavMesh()
    {
        ViveNavMesh mesh = (ViveNavMesh)target;

        Undo.RecordObject(mesh, "Update Navmesh Data");

        NavMeshTriangulation tri = NavMesh.CalculateTriangulation();

        Vector3[] verts = tri.vertices;
        int[]     tris  = tri.indices;
        int[]     areas = tri.areas;

        int vert_size = verts.Length;
        int tri_size  = tris.Length;

        RemoveMeshDuplicates(verts, tris, out vert_size, 0.01f);
        DewarpMesh(verts, mesh.DewarpingMethod, mesh.SampleRadius);
        CullNavmeshTriangulation(verts, tris, areas, p_area.intValue, mesh.IgnoreSlopedSurfaces, ref vert_size, ref tri_size);

        Mesh m = ConvertNavmeshToMesh(verts, tris, vert_size, tri_size);

        // Can't use SerializedProperties here because BorderPointSet doesn't derive from UnityEngine.Object
        mesh.SelectableMeshBorder = FindBorderEdges(m);

        serializedObject.Update();
        p_mesh.objectReferenceValue = m;
        serializedObject.ApplyModifiedPropertiesWithoutUndo();
        mesh.SelectableMesh = mesh.SelectableMesh; // Make sure that setter is called
    }
Exemple #29
0
 // Start is called before the first frame update
 public GraphGenerator(NavMeshTriangulation triangulization)
 {
     this.triangulization = triangulization;
     Graph    = new Dictionary <int, Node>();
     indices  = triangulization.indices;
     vertices = triangulization.vertices;
     GenerateGraph();
 }
Exemple #30
0
    static int CalculateTriangulation(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 0);
        NavMeshTriangulation o = NavMesh.CalculateTriangulation();

        LuaScriptMgr.PushValue(L, o);
        return(1);
    }