How to create separate collisions for 2D meshes?

Godot Version

4.6

Question

I want to add collisions to dynamically generated meshes in 2D but my current approach isn’t working.

var mdt := MeshDataTool.new()
mdt.create_from_surface(mesh, 0)

var polygon := PackedVector2Array()

for i in mdt.get_vertex_count():
	var vertex := mdt.get_vertex(i)
	polygon.append(Vector2(vertex.x, vertex.y))

First, this approach doesn’t create a collision shapes for each individual area. It should only create collisions for the walls in white.

Second, I get this error:

E 0:00:00:387   decompose_many_polygons_in_convex: Convex decomposing failed!
  <C++ Source>  core/math/geometry_2d.cpp:101 @ decompose_many_polygons_in_convex()

How can I fix these issues in a performant way? Are there built in functions I could use which I am unaware of? Thanks!

You need to provide your full code. You haven’t shown where the variable mesh is coming from, how it was constructed. You’re also using a 3D tool to create something in 2D. Which is why seeing how the mesh variable is created and assigned is important. You’re just discarding the z value, but if it’s not 0 in every case that could be part of your problem.

You also haven’t shown what you’re doing with the variable polygon after to turn it into a CollisionPolygon2D.

I recommend checking out this tutorial: Bite-Sized Godot: Pixel-perfect collision polygons on sprites - The Shaggy Dev as it does something similar to what you are trying to do.