How to count collision ?

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

Hello,

First projet, I try to make a labyrinth game you have to finish without touching walls. I want to count collision but it count collision each frame.

How can I count collision to make the player restart each 3 collisions ?

You’ll probably want to post your collision code to get any useful input. If/when you do that, please format it in your post. To do do that, paste the code, select it, and press the { } button in the forum editor’s tool bar.

jgodfrey | 2020-12-17 19:16

Sorry, I forgot the code (back in dev after several year)

    #détection de la collision avec un élément
	var collision = move_and_collide(velocity * delta)
	
	#gestion de la victoire ou du restart
	if collision :
		nbr_collision += 1
		
		# si la collision est avec le bloc de fin => victoire
		if collision.collider.name == 'Finish' :
			print ("C'est gagné !")
			print("Collision number ", nbr_collision)
		# si la collision n'est pas avec le bloc de fin et que c'est la 3eme => perdu => restart après quelques secondes
		else :
			if nbr_collision == 3 :
				print ("C'est perdu !")
				get_tree().reload_current_scene()

Enhide | 2020-12-17 19:35

:bust_in_silhouette: Reply From: jgodfrey

Completely untested, but you probably want something like the below. Really, it just uses a single boolean flag to track when you’ve collided with something (other than the Finish collider). Once you’re colliding, it won’t count any more collisions until you are back in a state where you are not colliding for at least one frame. At that point, the next collision will cause another increment of your counter.

var is_colliding = false

_physics_process(delta):
    var collision = move_and_collide(velocity * delta)

	if collision:
		if collision.collider.name == 'Finish' :
			print ("C'est gagné !")
			print("Collision number ", nbr_collision)
		else :
			if !is_colliding:
				is_colliding = true
				nbr_collision += 1
				if nbr_collision == 3 :
					print ("C'est perdu !")
					get_tree().reload_current_scene()
	else:
		is_colliding = false