Rigid bodies have this signal called body_entered. The body emits the signal whenever it collides with another one. Connect this signal to a function that increments a counter variable. When the counter reaches 10, you queue the body to be freed with queue_free.
So your ball’s script should look something like-
extends RigidBody2D
var collision_count = 0 #Your counter.
func increment_counter(obj): #This function is connected to the signal mentioned earlier.
collision_counter += 1
if collision_counter == 10:
queue_free()
Note: If you have other physics bodies that might potentially collide with it, you’ll need to test that obj parameter. It is the object the ball collided with. If it is not the walls then counter shouldn’t increment.
I must be doing something wrong. Seems like a simple thing…
I have created a function to connect with the body_entered signal. The GUI shows a green connection under the body_entered() signal and when I double click it, it goes to my function. I put a breakpoint in the function but it is never hit, even as the ball bounces around…
Have any ideas?
(edit) I tried doing it all in code, as shown below but still didn’t work:
I figured it out. Thanks for you help! I had to set contact_monitor to true and contacts reported > 0. It said so in the docs…don’t know how I missed that.