What's the best way to play a sound when two objects collide?

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


EDIT: I found the answer, I need to get the difference between the velocity pre-collision and post-collision, as explained here

I’m looking to play a sound effect when a RigidBody3D is hit by/hits another object. I’d also like the volume of the sound to be controlled by the collision’s force (i.e., a weak collision plays the sound quietly, but a strong one plays it louder)

I’ve figured that I could try to calculate the collision force based on the linear velocity of the two objects on collision, and use that to control the audio player’s volume property, like so:

func _on_body_entered(body):
    # Get the forces based on the colliding objects' velocities
    var forces
    if body == RigidBody3D:
	    forces = self.linear_velocity.length() + body.linear_velocity.length()
	    forces = self.linear_velocity.length()
    # Remap the forces variable to the appropriate volume range (this is a handy function I found online)
    var audio_volume = remap_range(forces, 1, 6, -50, 5)
    # Set the AudioStreamPlayer's volume accordingly
    $stream.volume_db = clamp(audio_volume, -50, 5)

However, I’m pretty sure there’s a much, much better and more reliable way of doing what I want to achieve… How could I improve this?

:bust_in_silhouette: Reply From: godot_dev_

You could have a node dedicated to handling sound effects, that way you won’t start polluting your collision logic with sound logic by instead signaling the collision occurred. This could be achieved via signals to create modularity in your code. The sound handler can connect to the collision signal and perform all the sound logic necessary

Alright, but that doesn’t really answer my question of how to affect the sound playback based on the strength of the impact between my RigidBody3D and other objects…

Voxybuns | 2023-04-21 13:48

:bust_in_silhouette: Reply From: erinorina

using only velocity may not be enough to accurately calculate the collision sound, here a video explaining why https://www.youtube.com/watch?v=MOYiVLEnhrw&t=9870s