How do you properly add a Rigidbody with Collision using GDScript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By avencherus
:warning: Old Version Published before Godot 3 was released.

In my scene I’m trying to dynamically add a rigid body with a collision capsule to a spatial scene. I have a static body collision plane below, so it works normally if I add the nodes in the scene tree through the editor, but not with code.

My coded rigid body shows having a collision capsule, but falls right through the plane. I hope that I’m overlooking something.

The code I have looks like this:

var rb = RigidBody.new()
rb.translate(Vector3(0,10,0))
rb.set_mode(2)
    	
var cs = CollisionShape.new()
cs.set_shape(CapsuleShape.new())
    
rb.add_child(TestCube.new())
    	
rb.add_child(cs)
    	
add_child(rb)

You should write set_mode(RigidBody.MODE_CHARACTER) instead of set_mode(2), it’s easier to understand and maintain :slight_smile:

Zylann | 2016-10-08 21:59

Neat, thanks. I see so you can use them like statics. I was wondering if there was a way to reach those constants from outside.

avencherus | 2016-10-09 06:40

:bust_in_silhouette: Reply From: Zylann

CollisionShape is an editor helper, it’s not really meant to be added as child during the game.
Instead, you should use add_shape: http://docs.godotengine.org/en/latest/classes/class_collisionobject.html?highlight=add_shape#class-collisionobject-add-shape.
Maybe this could fix your problem?

Edit: this works for me:

var body = RigidBody.new()
body.add_child(TestCube.new())
var shape = BoxShape.new()
body.add_shape(shape)
body.set_translation(Vector3(0,5,0))
add_child(body)

However, I would recommend creating a scene rather than building objects from script, it’s easier to do :slight_smile:

That’s what it was. I remember reading about them being helpers, but I couldn’t relocate the source.

The add and set shape didn’t jump out at me as I was still thinking they were methods of the RigidBody class. But now that I’m looking again, I apparently glossed over that I was looking at the CollisionObject parent class and not the RigidBody.

Thanks for helping me clear that up. X)

avencherus | 2016-10-09 06:47