Godot Version
v4.3.stable.mono.official [77dcf97d8]
VSCode with C#
Question
I am trying to create a voxel terrain with custom meshes. The weird thing I am running into is that after adding the custom mesh to the scene (through code), the positions of the meshes are incorrect.
See the following screenshot(s):
The black cube is a
MeshInstance3D
with a BoxMesh
placed in the scene through the editor at position (0, 0, -1) with scale (1, 1, 1). The white flat rectangles are 8 cubes I am trying to make through code.
As you can see, they are positioned with an offset (for a lack of a better term) while each position is (0, 0, 0), (1, 0, 0), (0, 0, 1) etc… The positions are correct, yet they are spread out for some reason.
But if I keep the code, but instead of custom meshes I place BoxMeshes it works as intended.
Like this:
This is how I also expect my custom meshes to be placed.
I think that I am missing a specific settings on the custom mesh that I need to set, but I can’t figure out what it is.
This is the code that generates the mesh:
public void GenerateMesh()
{
ArrayMesh customMesh = new ArrayMesh();
vertices = new List<Vector3>();
normals = new List<Vector3>();
indices = new List<int>();
uvs = new List<Vector2>();
// TOP
vertices.Add(Position + new Vector3(-0.5f, 0.5f, -0.5f));
vertices.Add(Position + new Vector3( 0.5f, 0.5f, -0.5f));
vertices.Add(Position + new Vector3( 0.5f, 0.5f, 0.5f));
vertices.Add(Position + new Vector3(-0.5f, 0.5f, 0.5f));
AddNormals(4, new Vector3(0, 1, 0));
AddQuad();
if (vertices.Count > 0)
{
var array = new Array();
array.Resize((int) Mesh.ArrayType.Max);
array[(int) Mesh.ArrayType.Vertex] = vertices.ToArray();
array[(int) Mesh.ArrayType.Normal] = normals.ToArray();
array[(int) Mesh.ArrayType.Index] = indices.ToArray();
// array[(int)Mesh.ArrayType.TexUV] = uvs.ToArray();
customMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, array);
// This creates the flat surfaces with an offset
Mesh = customMesh;
}
// This creates the correctly placed cubes
// Mesh = new BoxMesh();
}