Reputation: 21
I am making a voxel game in Unity, and is trying to generate terrain procedurally. While the terrain generator works, there's also very weird shadowing around the corners of the mesh. What can be the problem here?
My Generator script:
public class Generator : MonoBehaviour
{
private const int w = 2;
void Start()
{
WorldGenerator generator = new WorldGenerator(Vector2.zero, 0.015451f, 16.0f);
List<Vector3> vertices = new List<Vector3>();
List<int> indices = new List<int>();
int ind = 0;
for (int i = 0; i < w; i++)
for (int j = 0; j < w; j++)
{
Chunk chunk = generator.GenerateChunk(new Vector2Int(i, j));
Vector2 offset = new Vector2(i, j) * 16.0f;
for (int _i = 0; _i < 16; _i++)
for (int _j = 0; _j < 16; _j++)
for (int h = 0; h < 256; h++)
if (chunk.Blocks[_i, _j, h].BlockId > 0)
{
Vector3 position = new Vector3(offset.x + _i, h, offset.y + _j);
vertices.AddRange(this.vertices.Select(x => x + position));
if (CheckFaceAdd(chunk, new Vector3Int(_i, _j, h), new Vector3Int(-1, 0, 0))) //left
indices.AddRange(indicesLeft.Select(x => x + ind));
if (CheckFaceAdd(chunk, new Vector3Int(_i, _j, h), new Vector3Int(1, 0, 0))) //right
indices.AddRange(indicesRight.Select(x => x + ind));
if (CheckFaceAdd(chunk, new Vector3Int(_i, _j, h), new Vector3Int(0, 0, 1))) //top
indices.AddRange(indicesTop.Select(x => x + ind));
if (CheckFaceAdd(chunk, new Vector3Int(_i, _j, h), new Vector3Int(0, 0, -1))) //bottom
indices.AddRange(indicesBottom.Select(x => x + ind));
if (CheckFaceAdd(chunk, new Vector3Int(_i, _j, h), new Vector3Int(0, 1, 0))) //front
indices.AddRange(indicesFront.Select(x => x + ind));
if (CheckFaceAdd(chunk, new Vector3Int(_i, _j, h), new Vector3Int(0, -1, 0))) //back
indices.AddRange(indicesBack.Select(x => x + ind));
ind += 8;
}
}
Mesh mesh = GetComponent<MeshFilter>().mesh;
mesh.Clear();
mesh.vertices = vertices.ToArray();
mesh.triangles = indices.ToArray();
mesh.Optimize();
mesh.RecalculateTangents();
mesh.RecalculateNormals();
}
bool CheckFaceAdd(Chunk chunk, Vector3Int index, Vector3Int adj) {...}
Any help is appreciated.
Upvotes: 1
Views: 132
Reputation: 21
Nevermind I fixed it. Apparently my vertices were being smoothed due to sharing. I should have used 24 vertices per cube instead of only 8.
Upvotes: 1