How can I safely cache (pool) KinematicBody2D nodes?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bluepandion

I have an array of KinematicBody2D nodes that I use as bullets in my game. Whenever a bullet expires or collides, it is returned to the cache roughly like this:


Bullets are spawned again roughly like this:

new_bullet = bullet_array.pop_back()
new_bullet.position = spawn_position

Whenever I spawn a once used bullet, it sometimes gets killed by the same PhysicsBody2D that killed it originally - even though it has a completely new position. It’s as if the physics engine still considers it to be in the same position it died previously.

I’ve tried printing the position of the bullet when it dies and it is nowhere near the PhysicsBody2D that supposedly collided with it.

Am I missing some best practise that should be followed when caching physics objects?

Do you have any pending signal or connection that may need to be reset when adding again to scene?

I believe the technique is actually called object pooling try taking a look to this previous answer:

gioele | 2021-07-28 08:20

Thank you, using the correct terminology helped in finding much more information about it.

Apparently pooling is generally not recommended with Godot, but coming to that conclusion is not easy since the information is scattered about in many sources and not even mentioned in the official documentation.

My issue did not have any signals involved, but it does seem like I don’t even know half of the things to consider when removing nodes from the tree, resetting their state and putting them back.

Maybe I’ll just use simple instancing instead and see how far that gets in terms of performance.

bluepandion | 2021-07-29 05:51