How to set a mesh as a collision shape WITH GDSCRIPT

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ariel

How can you do this from GDSCRIPT I can’t find a parameter to instantiate a convect collision sibling from GDScript?
The child node that you are seeing in the code is meshinstance, but it does not have a parameter to create that kind of collision. The idea of this is to create many collisions

extends Spatial

var NodosHijos =  null#variable que va a guardar una lista de objetos

func _ready():
	NodosHijos = get_children()#toma todos los hijos
	
	for i in NodosHijos:
		#print(i.name)
		var mesh = i.get_child(0)#guardo el nodo meshinstance
		print(mesh.name)
		mesh.create_trimesh_collision() #no work
:bust_in_silhouette: Reply From: Zylann

At runtime, you can indeed use create_trimesh_collision() on the MeshInstance: MeshInstance — Godot Engine (3.1) documentation in English
It creates a child static body with the mesh as collision shape. How do you know it doesn’t work? It might be a bit impractical to customize though.

If you want to setup the node hierarchy yourself, you can instead generate only the Shape using the method of the same name from the Mesh resource directly: Mesh — Godot Engine (3.1) documentation in English
This returns a Shape which you can assign to a CollisionShape node, which you can itself place under a physics body of your choice.

Note: if your body is not static, you may want a convex shape, otherwise it won’t work.


Although, why do you need to create collisions at runtime? You can make them in the editor and turn the shapes on/off at runtime.

If you do it at runtime from an already-built Mesh, be aware that Godot actually downloads it back from the graphics card, builds a BVH, gives it to Bullet, which builds a BVH again. This is fine in editor but in game it’s 2 to 3 times slower than it should be.
This may be fine for a low amount of objects, but if you plan doing this on hundreds of meshes and experience performance issues, consider baking them in editor beforehands anyways.
If they are procedurally generated, there is a way to bypass the overhead but it’s only efficiently done using C++: Creating physics shapes is extremely slow · Issue #54 · Zylann/godot_voxel · GitHub

The problem is that they cannot be created in the editor I made this issue …
Create rigid bodies from many selected MESHs in the node viewer

ariel | 2019-09-17 11:38

I think they can if you select a MeshInstance, a menu should appear in the viewport toolbar with that option in it.

If you imported your model from Blender, you could also make collision shapes from there and exploit the importer by naming them with the *_col suffix: Importing 3D scenes — Godot Engine (3.1) documentation in English

However if you reaaaaally want to create them by hand in the editor, the menu doesn’t seem to work for multiple selection.

Zylann | 2019-09-17 17:27