- Home /
Question by
MakakWasTaken · Sep 24, 2015 at 12:11 PM ·
terrainmeshheightmap
Terrain Clone
I have been trying to clone my project for an system that I wanted to implement, but the problem is it turns out looking like this: Why is it ending up being this clunky?
Here is my code for the mesh generation:
int ChunkWidth = 250;
int ChunkCount = (int)Chunk.terrainData.size.x / ChunkWidth;
//Chunk is my terrain instance.
int hw = Chunk.terrainData.heightmapWidth;
float[,] heightmap = Chunk.terrainData.GetHeights(0,0,aw,aw);
Vector2 uvScale = new Vector2(1.0f / (hw- 1), 1.0f / (hw- 1));
for (int cx = 0; cx < ChunkCount; cx++)
{
for (int cy = 0; cy < ChunkCount; cy++)
{
GameObject water = new GameObject();
Vector3 p = new Vector3(cx * ChunkWidth, -1f, cy * ChunkWidth);
water.transform.position = p;
water.AddComponent<MeshRenderer>();
Mesh w = new Mesh();
MeshFilter mf = water.AddComponent<MeshFilter>();
Vector3[] vertices = new Vector3[ChunkWidth * ChunkWidth];
Vector2[] UV = new Vector2[ChunkWidth * ChunkWidth];
int[] triangles = new int[ChunkWidth * ChunkWidth * 6];
for (int y = (int)p.z; y < p.z + ChunkWidth; y++)
{
for (int x = (int)p.x; x < p.x + ChunkWidth; x++)
{
Vector2 curPos = new Vector2((x / Chunk.terrainData.size.x) * (hw-1), (y / Chunk.terrainData.size.z) * (hw- 1));
vertices[(y - Mathf.RoundToInt(p.z)) * ChunkWidth + (x - Mathf.RoundToInt(p.x))] = new Vector3((x - p.x), heightmap[Mathf.RoundToInt(curPos.y), Mathf.RoundToInt(curPos.x)] * Chunk.terrainData.size.y, (y - p.z));
UV[(y - (int)p.z) * ChunkWidth + (x - (int)p.x)] = Vector2.Scale(new Vector2(x, y), uvScale);
}
}
int index = 0;
for (int y = 0; y < ChunkWidth - 1; y++)
{
for (int x = 0; x < ChunkWidth - 1; x++)
{
triangles[index] = (y * ChunkWidth) + x;
triangles[index + 1] = ((y + 1) * ChunkWidth) + x;
triangles[index + 2] = ((y + 1) * ChunkWidth) + x + 1;
triangles[index + 3] = (y * ChunkWidth) + x;
triangles[index + 4] = ((y + 1) * ChunkWidth) + x + 1;
triangles[index + 5] = (y * ChunkWidth) + x + 1;
index += 6;
}
}
w.vertices = vertices;
w.uv = UV;
w.triangles = triangles;
w.RecalculateNormals();
w.Optimize();
mf.mesh = w;
yield return null;
}
}
EDIT: Another screenshot with wireframe turned on, where you can clearly see that the problem is the difference between the heightmap width and the actual terrain size. How can I make some interpolation to fix this?
problem.png
(338.7 kB)
untitled.png
(306.2 kB)
Comment
What is the heightmap resolution? If you select the wireframe with texture option and set opacity to 1 on your brush and use lower/raise on the vert here that is showing the issue, are you able to move it up or down in smaller increment?