0 votes

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!

in Engine by (12 points)

1 Answer

+2 votes

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)
            newAudio.transform.origin = -state.get_contact_local_position(i)
    elif state.get_contact_count() == 0 && !initial_hit:
        initial_hit = true
by (3,211 points)

Thank you so much!

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

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.