首頁>Game>source

我一直在使用Unity3D通過Perlin Noise生成地形,並且遇到了一个問题,即我構建的網格仅渲染一組三角形。

以下是我的MeshGeneration代碼:

using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using NUnit.Framework.Internal.Execution;
using UnityEngine;
public static class MeshGenerator
{
    public static MeshData GenerateMesh(float[,] heightMap)
    {
        int height = heightMap.GetLength(0);
        int width = heightMap.GetLength(1);
        int vertexIndex = 0;
        
        MeshData meshData = new MeshData(width, height);
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                meshData.vertices[vertexIndex] = new Vector3(x, heightMap[y, x], y);
                meshData.uvs[vertexIndex] = new Vector2( x/(float)width, y/(float)height);
                 
                // If we are not on the edge, then add two triangles to the mesh
                if ((x != width - 1) && (y != height - 1))
                {
                    meshData.AddTriangle(
                        vertexIndex,
                        vertexIndex + width,
                        vertexIndex + width + 1
                    );
                    meshData.AddTriangle(
                        vertexIndex,
                        vertexIndex + 1,
                        vertexIndex + width + 1
                    );
                }
                
                vertexIndex++;
            }
        }
        return meshData;
    }
}
public class MeshData
{
    public Vector3[] vertices;
    public Vector2[] uvs;
    public int[] triangles;
    public int triangleIndex;
    public MeshData(int meshWidth, int meshHeight)
    {
        vertices = new Vector3[meshWidth * meshHeight];
        uvs = new Vector2[meshWidth * meshHeight];
        triangles = new int[(meshWidth - 1) * (meshHeight - 1) * 6];
    }
    public void AddTriangle(int a, int b, int c)
    {
        triangles[triangleIndex] = a;
        triangles[triangleIndex + 1] = b;
        triangles[triangleIndex + 2] = c;
        triangleIndex += 3;
    }
    public Mesh CreateMesh()
    {
        Mesh mesh = new Mesh();
        mesh.vertices = this.vertices;
        mesh.uv = this.uvs;
        mesh.triangles = this.triangles;
        
        mesh.RecalculateNormals();
        return mesh;
    }
}

然後將我从MeshData.CreateMesh()获得的網格傳遞到以下函式中。

public void BuildMesh(MeshData meshData, Texture2D texture)
    {
        meshFilter.sharedMesh = meshData.CreateMesh();
        meshRenderer.sharedMaterial.mainTexture = texture;
    }

我正在關註本教程:https://www.youtube.com. com / watch?v = 4RpVByw1r5M&list = PLFt_AvwsXl0eBw2EiBtl_sxmDtSgzBxB3&index = 5

Mesh生成代碼的工作原理是建立頂點,uvs和三角形的陣列,並通過迭代由Perlin噪声建立的Vector3 [] heightMap来填充它们。

最新回復
  • 6月前
    1 #

    自己解決了這个問题 .其餘的三角形在網格的另一侧生成.這是我不知道頂點的順序必须是順時针順序。

相似問題

  • c++:如何在OpenGL中更新動態網格的索引?
  • control:Godot 3X實現俯仰,偏航和侧倾的平稳運動