Unity中的动态网格计算未正确索引三角形

3
我正在使用Unity构建游戏,想要生成一个由正方形瓦片组成的地图,并使用网格进行构建。但是出现了问题,我的网格无法正确渲染,最后一列和一半的列看不到。
以下是一些图片: 着色视图 线框视图 这是代码:
void GenerateMesh()
{
    mesh = GetComponent<MeshFilter>().mesh;
    mesh.Clear();

    Vector3[] vertices = new Vector3[(Map.WIDTH + 1) * (Map.HEIGHT + 1)];
    int nextIndex = 0;
    for (int x = 0; x <= Map.WIDTH; x++)
    {
        for (int y = 0; y <= Map.HEIGHT; y++)
        {
            vertices[nextIndex] = new Vector3(x * Square.SIZE, 0, y * Square.SIZE);
            nextIndex++;
        }
    }

    int[] triangles = new int[6 * Map.WIDTH * Map.HEIGHT];
    nextIndex = 0;
    for (int x = 0; x < Map.WIDTH; x++)
    {
        for (int y = 0; y < Map.HEIGHT; y++)
        {
            triangles[nextIndex] = x * Map.HEIGHT + y;
            triangles[nextIndex + 1] = x * Map.HEIGHT + y + 1;
            triangles[nextIndex + 2] = (x + 1) * Map.HEIGHT + y + 1;

            nextIndex += 3;

            triangles[nextIndex] = x * Map.HEIGHT + y;
            triangles[nextIndex + 1] = (x + 1) * Map.HEIGHT + y + 1;
            triangles[nextIndex + 2] = (x + 1) * Map.HEIGHT + y;

            nextIndex += 3;
        }
    }

    mesh.vertices = vertices;
    mesh.triangles = triangles;

}

Map.WIDTH、Map.HEIGHT和Square.SIZE是常量,它们的值分别为80、45、1。

提前致谢!


快速检查一下:如果将Map.WIDTH减少1(变为79),你是否看到相同的效果? - 3Dave
1个回答

2

您的第一个针对 y 值的内部循环使用了 <=

for (int y = 0; y <= Map.HEIGHT; y++)

因此,您的第二组循环应该使用Map.Height + 1进行索引计算:

for (int x = 0; x < Map.WIDTH; x++)
{
    for (int y = 0; y < Map.HEIGHT; y++)
    {
        triangles[nextIndex] = x * (Map.HEIGHT + 1) + y;
        triangles[nextIndex + 1] = x * (Map.HEIGHT + 1) + y + 1;
        triangles[nextIndex + 2] = (x + 1) * (Map.HEIGHT + 1) + y + 1;

        nextIndex += 3;

        triangles[nextIndex] = x * (Map.HEIGHT + 1) + y;
        triangles[nextIndex + 1] = (x + 1) * (Map.HEIGHT + 1) + y + 1;
        triangles[nextIndex + 2] = (x + 1) * (Map.HEIGHT + 1) + y;

        nextIndex += 3;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接