How does ImmediateMesh work?

Godot Version

4.2.0 C#

Question

I want to procedurally generate a mesh and update it every few second. Based on the docs I think I should use the ImmediateMesh.

I created a meshInstance and added a script with the following code.

public override void _Ready()
	{
		var mesh = new ImmediateMesh();
		mesh.SurfaceBegin(Mesh.PrimitiveType.Triangles);

		mesh.SurfaceAddVertex(new Vector3(0, 0, 0));
		mesh.SurfaceAddVertex(new Vector3(1, 0, 0));
		mesh.SurfaceAddVertex(new Vector3(1, 0, 1));

		mesh.SurfaceAddVertex(new Vector3(0, 0, 0));
		mesh.SurfaceAddVertex(new Vector3(0, 0, 1));
		mesh.SurfaceAddVertex(new Vector3(1, 0, 1));

		mesh.SurfaceEnd();

		Mesh = mesh;
	}

I expected a square to show up however it only shows a single triangle:

I’m trying to figure out what I’m doing wrong but most tutorials either only draw a triangle or are about one of the other procedural tools.

What to do?

That because of your drawing order.

Try do use this instead

mesh.SurfaceAddVertex(new Vector3(0, 0, 0));
mesh.SurfaceAddVertex(new Vector3(1, 0, 0));
mesh.SurfaceAddVertex(new Vector3(1, 0, 1));
// Start from where the last point ended
mesh.SurfaceAddVertex(new Vector3(1, 0, 1));
mesh.SurfaceAddVertex(new Vector3(0, 0, 1));
mesh.SurfaceAddVertex(new Vector3(0, 0, 0));
// And end here

The reason for that is that if you don’t specify your normals, the renderer will guess the normal direction based on the drawing order.

So you are actually drawing a quad. But one of your triangles is being culled because it has opposite normals. If you rotate your camera you’ll probably see the other triangle.

1 Like

Thanks you are right, you don’t want to know how much time I spend on this :stuck_out_tongue:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.