c# - 移除立方体地形的隐藏顶点和三角形
问题描述
我刚来这地方。我正在研究带有网格的程序地形。我开始制作一个像 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());
}
}
我只需要删除隐藏的顶点和三角形,但我不知道我该怎么做。
解决方案
诀窍是只生成玩家可见的三角形。因此,您不应该为每个体素生成立方体,而是为立方体的面的一个子集。
你这样做的方法是检查每个体素的所有 6 个面。如果给定的一侧与另一个体素接壤,则忽略该一侧并继续前进。如果边上没有体素,则将相应的立方体面添加到该边。这将产生一个包含整个地形或加载的地形的整体网格。
推荐阅读
- intellij-idea - 当我将 kotlin 与 Intellij IDEA 一起使用时,MAX_VALUE 被视为未注册的引用
- arrays - 过滤新对象时如何防止先前定义的对象更新(基于原始对象创建的新对象)
- javascript - Service Worker 不会在 chrome 中以离线模式缓存资产
- postgresql - PostgreSQL:分组然后过滤表,条件为不存在
- c# - 如何在不明确指定主键的情况下使用 Dapper Extensions 将对象插入 PostGreSql?
- magento2 - 如何在 Magento 2 中添加/更新客户 usnig REST Api 的送货地址
- git - git tag 命令过滤的分支名称
- javascript - JavaScript 日期到 Delphi TDateTime
- c# - C# 和电子邮件:HREF 到附加/嵌入在邮件本身中的文件
- c# - 为什么我的 DataTable.DefaultView.Sort 不按顺序排序?