Play a sound upon collision

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

I have a ball object (RigidBody2D) that plays a sound on collision. I set it up by using the body_entered signal, and playing the sound from there.
The issue with this is when two balls collide, each ball plays their sound at the same time, which is noticably loud.
Ideally, I want one sound to play per contact.

I’ve given it some thought and found something that seems to work, in the script attached to RigidBody2D:

var touched=false setget set_touched
func set_touched():
	touched=true

func _on_GenericBall_body_entered(body):
	if touched==false:
		print(str(self)+" hits "+str(body))
		$SoundHit.play()
		
	var other_node=body.get_owner().get_node(body.get_name())
	if other_node.has_method("set_touched"):
		other_node.set_touched()

func _on_GenericBall_body_exited(body):
	touched=false

I’d like to hear if there’s a better way.

That looks ok, but I think body.get_owner().get_node(body.get_name()) is unnecessary, you could just use body.

Zylann | 2019-01-16 14:06

Indeed, thanks.

zub_zob | 2019-01-16 14:48