首页>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来填充它们。

最新回答
  • 2021-1-2
    1 #

    自己解决了这个问题 .其余的三角形在网格的另一侧生成.这是我不知道顶点的顺序必须是顺时针顺序。

相关问题

  • c++:如何在OpenGL中更新动态网格的索引?
  • control:Godot 3X实现俯仰,偏航和侧倾的平稳运动