首页 > 解决方案 > 移除立方体地形的隐藏顶点和三角形

问题描述

我刚来这地方。我正在研究带有网格的程序地形。我开始制作一个像 Minecraft 这样的程序地形。而且我不知道如何删除隐藏块中的隐藏顶点和三角形。

隐藏的顶点和三角形

我的代码:

体素.cs:

using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshCollider))]
[RequireComponent(typeof(MeshRenderer))]
public class Voxel : MonoBehaviour {

    public Vector3[] vertices;
    public int[] triangles;

    public Vector3 pos;
    public GameObject chunk;
    Mesh mesh;

    public bool blockSolid;

    public Voxel(Vector3 position, GameObject obj)
    {
        pos = position;
        chunk = obj;
    }

    void Start () 
    {
        mesh = new Mesh();

        //Cube(0,0,0);
    }
    
    
    public void Cube(int x, int y, int z)
    {

        GameObject cube = new GameObject("Cubo");
        cube.AddComponent(typeof(MeshFilter));
        cube.AddComponent(typeof(MeshCollider));
        cube.AddComponent(typeof(MeshRenderer));
        cube.transform.parent = chunk.transform;
        mesh = cube.GetComponent<MeshFilter>().mesh;

        //cube.transform.position = pos;

        vertices = new Vector3[]
        {
            new Vector3(x,y,z),         // 0
            new Vector3(x,y+1,z),       // 1
            new Vector3(x+1,y+1,z),     // 2
            new Vector3(x+1,y,z),       // 3
            new Vector3(x+1,y,z+1),     // 4
            new Vector3(x+1,y+1,z+1),   // 5
            new Vector3(x,y+1,z+1),     // 6
            new Vector3(x,y,z+1)        // 7
        };

        triangles = new int[]
        {
            0,1,2,  0,2,3,              // Face frontal
            3,2,5,  3,5,4,              // Face direita
            0,7,6,  0,6,1,              // Face esquerda
            7,4,5,  7,5,6,              // Face traseira
            1,6,5,  1,5,2,              // Face superior
            0,3,4,  0,4,7               // Face inferior
        };

        UpdateMesh();
    }

    void UpdateMesh()
    {
        mesh.Clear();

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

        mesh.RecalculateNormals();
    }
}

块.cs:

using System.Collections.Generic;
using UnityEngine;

public class Chunk : MonoBehaviour {

    public int tx, ty, tz;
    public Vector3 pos;

    IEnumerator BuildChunk()
    {
        for (int x = 0; x < tx; x++)
        {
            for (int y = 0; y < ty; y++)
            {
                for (int z = 0; z < tz; z++)
                {
                    pos = new Vector3(x,y,z);
                    Voxel block = new Voxel(pos, this.gameObject);

                    block.Cube(x,y,z);
                    yield return null;
                }
            }
        }
    }

    void Start () 
    {
        StartCoroutine(BuildChunk());
    }
}

我只需要删除隐藏的顶点和三角形,但我不知道我该怎么做。

标签: c#unity3d

解决方案


诀窍是生成玩家可见的三角形。因此,您不应该为每个体素生成立方体,而是为立方体的面的一个子集。

你这样做的方法是检查每个体素的所有 6 个面。如果给定的一侧与另一个体素接壤,则忽略该一侧并继续前进。如果边上没有体素,则将相应的立方体面添加到该边。这将产生一个包含整个地形或加载的地形的整体网格。


推荐阅读