How to enable/disable a StaticBody2D?

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

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.

:bust_in_silhouette: Reply From: zendorf

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
:bust_in_silhouette: Reply From: Bojidar Marinov

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 :)

:bust_in_silhouette: Reply From: kjav

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

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

kidscancode | 2018-04-12 21:04

@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.

jjmontes | 2020-08-17 12:56