Hello all, I’m just starting out with Unity and coding in general and hope to learn a lot here!
I have a vehicle with sphere colliders for wheels, and want the wheels to play tire sounds while it is touching the ground, and stop playing the sound while airborne.
I’ve used the following basic javascript to do this so far:
function OnCollisionEnter(collision : Collision) {
audio.Play();
print("front wheel collide enter");
}
function OnCollisionExit(collision : Collision) {
audio.Pause();
print("front wheel collide EXIT");
}
This almost works, however the problem is that when the wheel bounces even slightly off the ground, the audio is of course stopping - even when it’s not visible to the player that it has left the ground for a fraction of a second. This results in the wheel sounds stopping and starting more than I’d like, and sounds glitchy.
Ideally I’d like it to continue playing the sound unless the wheel has actually left the ground for more than a fraction of a second without colliding once more… so that to the player it appears seemless.
This should get you in the right direction but I haven’t used Javascript in a while:
var delay = 0.0;
var pauseTime = .5;
var onGround = false;
onCollisionEnter…{
delay = 0;
onGround = true;
audio.Play();
}
onCollisionExit…{
onGround = false;
}
Update(){
if(!onGround){
delay += Time.deltaTime;
if(delay>pauseTime)audio.Pause();
}
}
Thanks for your help, I’ve got it working better than before now.
Its still not perfect, it seems tricky getting it balanced between precise stopping/starting of sound as it becomes airborne, and not sounding glitchy with detection of colliders. Maybe theres something else happening on my test track, as the audio script seems to have issues with some areas of the track as far as detecting the collision enter/exit correctly. I’ve got a test track made from a series of flattened cubes and occasionally the vehicle seems not to register the fact that the wheels are colliding with some sections of track surface.
I haven’t played around with cars, but you may want to use only one collider and possibly not a wheel, but in the center of the car. If it doesn’t have physical collision, like a trigger or something, it may be more accurate. You could also cast a ray and use the distance to the ground.