I’ve been trying to track down a cause of an error in some code for several days now, and I just can’t seem to find it. Normally I would try to find which variables are not as they should be, and then use the “wolf fence algorithm” to find exactly where the cause is, but I have no way of knowing when variables are wrong or not in this case. I’ve tried checking all the variables I can, and they all seem to be correct.
The problem isn’t the wrong normals. When the player moves, new chunks are loaded, towards where the player is walking, making the world “infinite”. The problem is the chunks are often being loaded… incorrectly. I’m not sure how to describe it, but the blocks are in the wrong places, making floating chunks, and large cliffs between some chunks. It’s best if you just try it yourself by moving the character controller to new locations and watch how the new chunks get created.
Code can be found at Terrain generation error - Pastebin.com.
To get it working, just add a character motor tagged “Player”, and a gameObject with the “terrainGen” script attacked. You will also need to save the priorityQueue and chunkVec scripts as assets. No console output happens whatsoever.
The only thing I can see at once that’s missing is the normals of the cubes, thus the lighting is wrong. This can be fixed by simply moving the mesh.RecalculateNormals() call further down:
Mesh mesh = new Mesh();
mesh.vertices = vertices.ToArray();
// mesh.RecalculateNormals(); // this is too early
mesh.uv = uvs.ToArray();
mesh.triangles = triangles.ToArray();
mesh.RecalculateNormals(); // triangles are needed before normals can be calculated
mesh.RecalculateBounds(); // I would do this as well
Then it looks like this:
[OP said that the normals weren’t the original problem]
The problem definitely lies within your GenerateChunks and ShiftLoadedChunks method (moving the player and calling Generate all the time works as expected). I would start by trying to restate your algorithm in a way that doesn’t involve try-catch as integral part of the solution.
Also, I don’t know why you need that priority queue and 1-s-generating-delay at all. I think you could just go through your chunks, delete the ones not matching the player position anymore, and generating new ones on the opposite side.
If that’s too resource intense, I would add exactly that objects to the generating queue and generate them one at a time after sorting by distance to the player (you seem to currently have quite a complicated way of doing that - you should think about your data structure).