Solved - Problems generating QuadMesh for terrain. Won't use 4 points

Godot Version

4.4

Question

Hi all, I am trying to make a custom terrain system (tried some addons, but I need some custom stuff for mine) but I am having some trouble spawning the quads, and not sure what is up. I have a system where I first spawn points (just small spheres) that are the corners of all locations, then another button for actually spawning the quads. The spheres work fine and I can manipulate them as I need, but the spawning of the quads isn’t working right.

The code I have right now:

func spawn_quads():
	quads.clear()
	for s in range(spheres.size()):
		var sphere = spheres[s]
		if sphere.position.x < chunk_size.x - 2 and sphere.position.z < chunk_size.y - 2:
			var a = sphere.global_position + Vector3(0,0,0)
			var b = sphere.global_position + Vector3(1,0,0)
			var c = sphere.global_position + Vector3(0,0,1)
			var d = sphere.global_position + Vector3(1,0,1)
			
			create_quad(a, b, c, d)

func create_quad(a: Vector3, b: Vector3, c: Vector3, d: Vector3):
	var st = SurfaceTool.new()
	st.begin(Mesh.PRIMITIVE_TRIANGLES)
	
	st.add_vertex(a)
	st.add_vertex(b)
	st.add_vertex(c)
	st.add_vertex(d)
	
	#Triangle 1
	st.add_index(0)
	st.add_index(1)
	st.add_index(2)
	
	#Triangle 2
	st.add_index(1)
	st.add_index(3)
	st.add_index(2)
	
	st.generate_normals()
	
	var mesh = st.commit()
	
	var new_quad = MeshInstance3D.new()
	new_quad.mesh = mesh
	self.add_child(new_quad)
	quads.append(new_quad)

Its nothing complex (yet!) and it works for the most part. But if I edit the location of a sphere before spawning the quads, this is what happens:

As you can see, the quad spawns but its flat and at the height of the highest sphere. What I need though is for all 4 points of the quad to be at the locations of the spheres. What is going wrong here? How do I fix this?

Found the problem, I was using the same sphere for each corner of the calculation. Easy fix!

func spawn_quads():
	quads.clear()
	
	for x in range(chunk_size.x - 1):
		for y in range(chunk_size.y - 1):
			var index = x * chunk_size.y + y
			
			var s00 = spheres[index]                        # lower-left sphere at (x, y)
			var s10 = spheres[index + chunk_size.y]         # lower-right sphere at (x+1, y)
			var s01 = spheres[index + 1]                      # upper-left sphere at (x, y+1)
			var s11 = spheres[index + chunk_size.y + 1]       # upper-right sphere at (x+1, y+1)
			
			# Use the global position of each sphere to determine the quad's corners.
			# If needed, use global_transform.origin instead of global_position.
			var a = s00.global_position  # lower-left vertex
			var b = s10.global_position  # lower-right vertex
			var c = s01.global_position  # upper-left vertex
			var d = s11.global_position  # upper-right vertex
			
			create_quad(a, b, c, d)
1 Like