I am writing a simple heightmap-based terrain engine for use with Unity iPhone. I have written a Chunk2D class that generates the vertices/triangles for a section of heights from my global heightmap. Everything seems to be working pretty well when the landscape is fairly smooth, but the second I start to get sharp edges the triangles start to flicker.
I have uploaded an example of the problem here: http://emerganz.com/terraintest/WebPlayer.html
Here is the part of my chunk class where I generate the geometry:
// vdx, vdy = number of vertices in X and Y of the grid
public void Generate() {
float z;
int i=0;
int t=0;
for(int x=0; x<vdx; x++) {
for(int y=0; y<vdy; y++) {
// Generate vertices
z = (heights[x,y] + heights[x,y+1] + heights[x,y+1] + heights[x+1,y+1]) / 4;
vertices[i].x = offsetX + x * scaleX;
vertices[i].y = offsetZ + z * scaleZ;
vertices[i].z = offsetY + y * scaleY;
uvs[i].x = x * scaleU;
uvs[i].y = y * scaleV;
// Generate triangles
if((x>0) (y>0)) {
triangles[t++] = i - vdx - 1;
triangles[t++] = i;
triangles[t++] = i - 1;
triangles[t++] = i - vdx - 1;
triangles[t++] = i - vdx;
triangles[t++] = i;
}
i++;
}
}
}
Here’s the code from my simple test scene where I create the mesh:
private void GenerateMesh() {
chunk = new Chunk2D(dx, dy, heightMap, typeMap);
Mesh mesh = new Mesh();
MeshFilter meshFilter = GetComponent<MeshFilter>();
meshFilter.mesh = mesh;
mesh.vertices = chunk.vertices;
mesh.uv = chunk.uvs;
mesh.triangles = chunk.triangles;
mesh.RecalculateNormals();
}
I’m pretty much at a loss here - only 2 options I can imagine would be:
a) Calculating normals myself could help?
b) Angles > 45 degrees cannot be smoothed. Giving each triangle its own set of vertices might work?
I haven’t decided if I want a smooth or a sharp look on the triangles in the landscape - preferably I’d like to make it a configurable option.