Count collisions

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

I have a bouncing ball (RigidBody2D) l that collides with walls (StaticBody2D). I want to allow the ball to bounce/collide 10 times then delete.

How can I go about counting each collision like that so I can know when the ball has bounced 10 times?

Thanks in a advance!

:bust_in_silhouette: Reply From: SIsilicon

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:

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:

self.connect("body_entered", self, "_on_body_entered")


func _on_body_entered(body):

     bounce_cnt += 1


tproper | 2018-05-11 22:35

I’ll look into it as soon as I’m on Godot again.

SIsilicon | 2018-05-12 00:52

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.

Thanks again.

tproper | 2018-05-12 00:55