I want to add some walls and obstacles the simplest collision shape possible (a box) and I was wondering if there is a way to automatically add from the editor a CollisionShape3D that matches the size and bounds of a mesh instance. Just like you can use the menu “Mesh → Create collision shape…” for adding more complex collisions (trimesh, single convex…) but lacks this more simple box approach.
I just want to automatically create box collision shapes that matches exactly that orange cube that the editor is drawing around the model.
Let’s say you have an MeshInstance3d called object that has its own mesh called objectMesh applied:
var collision_shape = CollisionShape3D.new()
collision_shape.shape = objectMesh.create_trimesh_shape()
var static_body = StaticBody3D.new()
static_body.add_child(collision_shape)
object.add_child(static_body)
I am not sure if this will work or will lead to solve your situation, I only have experience with array meshes.
Our approach is to create a new CollisionShape3D object with its shape formed by our mesh input. Then we add this CollisionShape3D to an appropriate node that can make use of it (like a StaticBody3D) which we will then add to the MeshInstance3D object.
The Object Tree looks like this:
MeshInstance3D root-node + mesh
StaticBody3D
CollisionShape3D has collision data based on the mesh
But the method you described adds a trimesh shape with the shape of the mesh (just like the menu “Mesh → Create Collishion Shape…”). What I’m trying to achieve is to create a box collision shape with the dimensions and positioning of the mesh.
Well I have created a function that does exactly what I want. It looks like this:
@export var mesh_instance : MeshInstance3D
func create_box_collision_shape():
if not mesh_instance: return
if not mesh_instance.mesh: return
var box_collider = CollisionShape3D.new()
box_collider.shape = BoxShape3D.new()
var aabb = mesh_instance.get_aabb()
box_collider.shape.size = aabb.size
box_collider.position = aabb.position + aabb.size / 2
add_child(box_collider)
box_collider.owner = self
I was going to post a proposal for adding this to the Mesh “Add Collision Shape” context menu for convenience but I have found that there is already a proposal for it here.