Vehicle body collisions

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

Hi!
I’m learning Godot and I’m wondering if there’s a way to handle collisions between my vehicle body and my walls which are static bodis. I want a sound to be played when my car collides with the wall. Can you help me? Thanks!

:bust_in_silhouette: Reply From: Magso

This is a long script I have that plays a sound when the rigid/vehicle body hits something. It plays the sound at the hit position and alters the volume according to impact.

extends VehicleBody

export var fallback_audio_clip : AudioStream
export var group_name_and_audio_clip = {}
var initial_hit = true

func _init():
	if !contact_monitor:
		contact_monitor = true
	if contacts_reported < 2:
		contacts_reported = 2

func _integrate_forces(state):
	if state.get_contact_count() > 0 && initial_hit:
		initial_hit = false
		for i in state.get_contact_count():
			var newAudio = AudioStreamPlayer3D.new()
			var groups = state.get_contact_collider_object(i).get_groups()
			var fallback = true
			for this in groups.size():
				if group_name_and_audio_clip.has(groups[this]):
					fallback = false
					newAudio.stream = group_name_and_audio_clip[groups[this]]
			if fallback:
				newAudio.stream = fallback_audio_clip
			newAudio.unit_db = state.get_contact_impulse(i)
			add_child(newAudio)
			newAudio.transform.origin = -state.get_contact_local_position(i)
            newAudio.play()
			yield(newAudio,"finished")
			newAudio.queue_free()
    elif state.get_contact_count() == 0 && !initial_hit:
		initial_hit = true

Thank you so much!

Stefano Gini | 2020-04-06 06:58

Sorry for offtopic, but one thing in your code doesn’t seem good, i mean this:

if !contact_monitor:
    contact_monitor = true
if contacts_reported < 2:
    contacts_reported = 2

I’m talking about your “if” clauses here, you don’t need to check what a variable is equal to before setting to a certain value, these are just odd strings in code and extra operations for processor. I recommend the following instead:

contact_monitor = true
contacts_reported = 2

GreyMiller | 2020-04-06 11:31

To be honest you’re right about contact_monitor = true but contacts_reported = 2 should only be set if it’s below 2 just so it doesn’t cause any potential errors else where in the project.

Magso | 2020-04-06 12:54