Godot Version
4.3
Question
I observed an interesting (weird) behavior regarding collisions when adding/removing nodes in the scene tree.
I created a scene that just contains an Area2D and a CharacterBody2D. They are stacked on top of each other (collision triggers on game start but this is not necessary to reproduce this, they just need to be on top of each other when removing the node from the scene tree, I explain this more later).
Then I made a function that just moved the CharacterBody2D by 50 pixels to the right (putting it outside of the Area2D collider). It triggers if I press space. I started the project, collision triggers, I press “space”, the body moves out, I can even move it around with WASD and collision does no re-trigger as one would expect (unless I go back into the collision zone).
Then I put this scene as a child of a Node2D and made it so the Node2D calls remove_child
on it (but still preserves it in a variable). So the CharacterBody is moved 50px and the scene gets removed from the scene tree. I made it so another press of space just adds the node back to the tree with add_child
and observed the collision triggering again even though the CharacterBody is outside the collision area.
I assume Godot requires a tick to actually move the CharacterBody and that does not happen when detached. Then when it inserts the subtree back into the scene tree the collision is triggered before the move is registered which kinda makes sense but is till a bit weird to me. I would expect collision to not re-trigger.
My question here is: Is there a way to prevent this behavior? Is it even expected or should I report it?
If anyone wants it I can post a minimal reproduction project. This is how the scene tree looks, Sprite2Ds are just added to have a visual representation. ColliderTestScene is the one that gets removed and added.
ColliderTest
┖╴ColliderTestScene
┠╴Area2D
┃ ┠╴Sprite2D
┃ ┖╴CollisionShape2D
┖╴CharacterBody2D
┠╴Sprite2D
┠╴CollisionShape2D
┖╴Camera2D