I have been trying to generate a mesh based on some noise, and I want to say if the noise is 0 don’t generate a vertices. But the problem is that the mesh will end up look really weird because of the way I generate my triangles.
Code:
private void CreateMesh()
{
var m = new RidgeNoise(Random.seed);
m.OctaveCount = 2;
m.Frequency = 0.01f;
int hw = Terrain.activeTerrain.terrainData.heightmapWidth;
float[,] heightmap = Terrain.activeTerrain.terrainData.GetHeights(0, 0, hw, hw);
int ChunkWidth = hw / 8;
int ChunkCount = hw / ChunkWidth;
float scale = Terrain.activeTerrain.terrainData.size.x / hw;
Vector2 uvScale = new Vector2(1.0f / hw, 1.0f / hw);
for (int cx = 0; cx < ChunkCount; cx++)
{
for (int cy = 0; cy < ChunkCount; cy++)
{
int CW = hw / ChunkCount;
GameObject water = new GameObject();
Vector3 p = new Vector3(cx * ChunkWidth, 0f, cy * ChunkWidth);
water.transform.localScale = new Vector3(scale, 0.95f, scale);
water.transform.position = new Vector3(cx * (ChunkWidth * scale), 0f, cy * (ChunkWidth * scale));
water.name = "Water";
water.transform.parent = Terrain.activeTerrain.transform;
water.AddComponent<MeshRenderer>();
Mesh w = new Mesh();
MeshFilter mf = water.AddComponent<MeshFilter>();
Vector3[] tVertices = new Vector3[(CW + 1) * (CW + 1)];
Vector2[] tUV = new Vector2[tVertices.Length];
int[] triangles = new int[tVertices.Length * 6];
for (int y = 0; y < CW; y++)
{
for (int x = 0; x < CW; x++)
{
Vector2 curPos = new Vector2((p.x + x), (p.z + y));
float height = heightmap[(int)curPos.y, (int)curPos.x] * Terrain.activeTerrain.terrainData.size.y;
if (height < WaterLevel)
{
height = WaterLevel;
}
float v = Mathf.Max(0f, m.GetValue(curPos.x, curPos.y, 0f) - 0.875f) / 25.0f;
map.SetPixel((int)curPos.x, (int)curPos.y, Color.white * (v * 25));
if (v != 0)
{
tVertices[y * CW + x] = new Vector3(x, height, y);
tUV[y * CW + x] = Vector2.Scale(new Vector2(x, y), uvScale);
heightmap[(int)curPos.y, (int)curPos.x] -= v;
}
}
}
int index = 0;
for (int y = 0; y < CW - 1; y++)
{
for (int x = 0; x < CW - 1; x++)
{
triangles[index] = (y * CW) + x;
triangles[index + 1] = ((y + 1) * CW) + x;
triangles[index + 2] = ((y + 1) * CW) + x + 1;
triangles[index + 3] = (y * CW) + x;
triangles[index + 4] = ((y + 1) * CW) + x + 1;
triangles[index + 5] = (y * CW) + x + 1;
index += 6;
}
}
w.vertices = tVertices;
w.uv = tUV;
w.triangles = triangles;
w.RecalculateNormals();
w.Optimize();
mf.mesh = w;
}
}
}
Noise:
Result: