Car sound with respect to speed?

1.3k Views Asked by At

I need my car sound pitch to be changed with respect to speed. Current I am using the solution of an answer which is :https://answers.unity.com/questions/1067016/car-engine-sound-code-unity5car-engine-sound-code.html

public float topSpeed = 100; // km per hour
private float currentSpeed = 0;
private float pitch = 0;

void Update () 
{
     currentSpeed = transform.GetComponent<Rigidbody>().velocity.magnitude * 3.6f;
     pitch = currentSpeed / topSpeed;

     transform.GetComponent <AudioSource> ().Pitch = pitch;
}

As per this the starting pitch is 0 And it changes as per my currentSpeed I.e - currentSpeed/topSpeed so when my current speed = topSpeed the pitch will be 1 and it's good approach But in my case it plays the sound but when once my car reaches topSpeed it stops playing sound than and never plays it again even if I brake and start from zero speed

As I am an beginner intermediate I think it's because of my rigidbody of car is kinematic but I don't know the correct reason and any solution of this.

1

There are 1 best solutions below

0
DenizBey On

İ know it's too late to answer it. But maybe it helps for other people who have same issue.

this is the simplest way you can do with one sound,

type this to Vehicle controller script

 //Vehicle's rigidbody
 Rigidbody _rigidBody;
  
 //You have to assign in a sound
 public AudioSource _shipSound;
 float EngineAcceleration = 10f;

 private void Start()
 {
    _rigidBody = GetComponent<Rigidbody>(); 
    _SoundShip.Play();  
 }
 private void Update()
 {
   //simply we divide Rigidbody speed to ourAcceleration
  _SoundShip.pitch = Mathf.Clamp(_rigidBody.velocity.magnitude / 
  EngineAcceleration , 
  minEngineSound, maxEngineSound);
 }