Is it possible to create a box CollisionShape3D that automatically matches the bounds of a MeshInstance?

Godot Version

4.3

Question

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.

Thank you in advance.

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

Hi! Thank you for your answer.

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.

Greetings.

Then I believe you can just create a BoxShape3D and set the shape as you need?

It might be even easier because as a Box, you only need to set x, y and z.

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.

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