我正在使用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。
提前致谢!
答案 0 :(得分: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;
}
}