I am trying to do something like Minecraft game in Unity. Currently I am trying to generate a chunk of blocks, given dimensions. I can successfully create a chunk of N x 0 x 0 sized chunk, but due to lack of logic, I have no idea on how to make triangles and vertices match for other blocks.
Basically, what I mean is, I can generate something like this:
But can't do this:
My Block vertices and Triangles:
Vector3[] cVerts = {
new Vector3 (0, 0, 0), //0
new Vector3 (1, 0, 0), //1
new Vector3 (1, 1, 0), //2
new Vector3 (0, 1, 0), //3
new Vector3 (0, 1, 1), //4
new Vector3 (1, 1, 1), //5
new Vector3 (1, 0, 1), //6
new Vector3 (0, 0, 1), //7
};
int[] cTris = {
0, 2, 1, //face front
0, 3, 2,
2, 3, 4, //face top
2, 4, 5,
1, 2, 5, //face right
1, 5, 6,
0, 7, 4, //face left
0, 4, 3,
5, 4, 7, //face back
5, 7, 6,
0, 6, 7, //face bottom
0, 1, 6
};
Chunk creation method:
void CreateChunk(){
...
for (int x = 0; x < 100; x++)
{
for(int y = 0; y < 10; y++){
for (int z = 0; z < 1; z++)
{
AddBlockAtPosition(new VectorInt(x, y, z), "Grass");
}
}
}
ChunkMesh.vertices = CurrentChunkVerts.ToArray();
ChunkMesh.triangles = CurrentChunkTris.ToArray();
//ChunkMesh.uv = uvs.ToArray();
ChunkMesh.RecalculateNormals();
}
AddBlockAtPosition() method:
void AddBlockAtPosition(VectorInt pos, string name)
{
int x = pos.x, y = pos.y, z = pos.z;
//create separate cube data
CubeMesh cube = new CubeMesh(vertices.ToArray(), triangles.ToArray(), uvs.ToArray());
//I use MoveCube() to change each Block's vertex and triangle numbers, so they will "match" in a Chunk mesh, when they become part of it.
cube.MoveCube(new Vector3(x, y, z), (x + y + z) * 8);
//cube.MoveUV(new Vector2(x + y + z, x + y + z));
CurrentChunkVerts.AddRange(cube.Vertices());
CurrentChunkTris.AddRange(cube.Triangles());
//CurrentChunkUV.AddRange(cube.UVs());
}
And most importantly, that's where my problems are, MoveCube();
Class Cube{
private Vector3[] vertices;
private int[] triangles;
...
public void MoveCube(Vector3 direction, int n)
{
for(int i=0; i<vertices.Length; i++)
{
vertices[i] += direction;
}
for (int i = 0; i < triangles.Length; i++)
{
triangles[i] = triangles[i] + n;
}
}
}
I know that I am not the first to re-create minecraft, I have found this tutorial https://www.blockstory.net/node/56
But for me as a beginner, some "simple" parts like these I have problems with are skipped. And other tutorials just generalize the idea, which isn't enough for me.