+4 votes

How do I enable or disable a StaticBody2D from script?
I don't see any auto-complete function that seem to do that. I tried show() and hide() but it does nothing.

in Engine by (28,833 points)

3 Answers

0 votes

It is a good question, as there doesn't seem to be a way to disable the StaticBody2D node itself.

My workaround was to turn on the "Trigger" flag on the child CollisionShape2D. This will have the effect that kinematic and rigid bodies can pass through the static body. As the documentation states "A trigger shape detects collisions, but is otherwise unaffected by physics".

Just turn this flag on to disable physics. For example, assuming you have a child CollisionShape2D to your StaticBody2D node, a script on the StaticBody2D would do something like:

var cs = get_node("CollisionShape2D")        # get child collision shape node
cs.set_trigger(true)                         # turn the trigger flag on to disable physics
by (268 points)
+4 votes

There is a way to do it. Just set the layer make and the collision mask to 0. E.g.:

var old_layer_mask = 0
var old_collision_mask = 0
func enable():
    set_layer_mask(old_layer_mask)
    set_collision_mask(old_collision_mask)
func disable():
    old_layer_mask = get_layer_mask()
    old_collision_mask = get_collision_mask()
    set_layer_mask(0)
    set_collision_mask(0)

Note that the above code is not idiot-proof, and if you call enable before disable, it would loose collision forever (but you can fix it). That's how it goes with example code :)

by (1,594 points)
–3 votes

Since this question was asked, Godot 3 was released with a new feature; the "disable" variable on StaticBody2D / RigidBody2D. You can now disable a StaticBody2D like this:

var body = get_node("StaticBody2D")
body.disabled = true
by (26 points)

This is incorrect. disabled is a property of CollisionShape2D, not the physics body.

@kidscancode is right, also, when restoring a CollisionShape2D via disabled = false it seems not to produce collisions anymore. I resorted to using the masks as per @Bojidar answer.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.