Godot Version
4.4
Question
I am making a tool for generating voxel terrain. it works well but the spacing can be messed up when i change the resolution.
i believe chunk_size should be " chunk_size * resolution " and the spacing problem has to do with how chunk.position as it is calculated using chunk_size and offset_x and y. so that might be part of the problem and i cant figure out how to fix it i tried a number of options but couldnt figure it out.
if chunk size is 10 resolutions 1,2,5, and 10 do not cause gaps in between chunks but any other number does probably cause chunk.position is divided by 2.
func generate_chunks() → void:
# Clear existing chunks and splatmaps
for child in get_children():
if child is MeshInstance3D and child != brush_preview:
child.queue_free()
chunk_splatmaps.clear()
chunk_splatmap_images.clear()
var vertex_count: int = int(floor(float(chunk_size) / resolution)) + 1
for chunk_x in range(chunks_x):
for chunk_z in range(chunks_z):
var surface_tool := SurfaceTool.new()
surface_tool.begin(Mesh.PRIMITIVE_TRIANGLES)
var offset_x: float = chunk_x * chunk_size
var offset_z: float = chunk_z * chunk_size
print("Generating chunk %d_%d with offset_x=%f, offset_z=%f" % [chunk_x, chunk_z, offset_x, offset_z])
# Generate vertices with local UVs
for x in range(vertex_count):
for z in range(vertex_count):
var local_x: float = min(x * resolution, chunk_size)
var local_z: float = min(z * resolution, chunk_size)
var global_x: float = offset_x + local_x
var global_z: float = offset_z + local_z
var noise_val: float = noise.get_noise_2d(global_x, global_z)
var height: float = noise_val * height_scale
var pos := Vector3(local_x, height, local_z)
var uv := Vector2(local_x / chunk_size, local_z / chunk_size)
surface_tool.set_uv(uv)
surface_tool.add_vertex(pos)
# Debug vertex positions at corners
if (x == 0 or x == vertex_count - 1) and (z == 0 or z == vertex_count - 1):
print("Chunk %d_%d, Vertex (%d, %d): local=(%f, %f), global=(%f, %f)" % [chunk_x, chunk_z, x, z, local_x, local_z, global_x, global_z])
# Generate indices
for x in range(vertex_count - 1):
for z in range(vertex_count - 1):
var i: int = x + z * vertex_count
surface_tool.add_index(i)
surface_tool.add_index(i + vertex_count)
surface_tool.add_index(i + 1)
surface_tool.add_index(i + 1)
surface_tool.add_index(i + vertex_count)
surface_tool.add_index(i + vertex_count + 1)
surface_tool.generate_normals()
var mesh := surface_tool.commit()
# Create chunk
var chunk := MeshInstance3D.new()
chunk.mesh = mesh
chunk.name = "Chunk_%d_%d" % [chunk_x, chunk_z]
chunk.set_layer_mask_value(1, true)
chunk.position = Vector3(offset_x - (chunks_x * chunk_size / 2.0), 0, offset_z - (chunks_z * chunk_size / 2.0))
# Create chunk-specific material
var chunk_material = default_material.duplicate()
chunk.set_surface_override_material(0, chunk_material)
add_child(chunk)
chunk.owner = get_tree().edited_scene_root
print("Generated chunk: ", chunk.name, " at position: ", chunk.position)