How to add an engine sound to a car with respect to its speed in Unity



I made a pickup car with its wheel colliders and completely working. I can controll it to move by pressing arrow keys on my keyboard. The next thing I need to do is to add engine sound audio file to the car with respect to its movement speed. So when the car is running fast the audio pitch must be increased, and also decreased when the car is slowing down and stopping.

There are 2 scripts in this video. First is this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyCarController : MonoBehaviour
{
	
	public List<AxleInfo> axleInfos;
	public float maxMotorTorque;
	public float maxSteeringAngle;
	
	public static MyCarController cc;
	
	public float carMaxSpeed = 100;
	public float carCurrentSpeed = 0;
	
	Rigidbody rb;
	
	public void Start(){
		cc = this;
		rb = GetComponent<Rigidbody>();
	}
	
	public void ApplyLocalPositionToVisuals(WheelCollider collider){
		if(collider.transform.childCount == 0){
			return;
		}
		Transform visualWheel = collider.transform.GetChild(0);
		Vector3 position;
		Quaternion rotation;
		collider.GetWorldPose(out position, out rotation);
		
		visualWheel.transform.position = position;
		visualWheel.transform.rotation = rotation;
	}

    public void FixedUpdate()
    {
		
        float motor = maxMotorTorque * Input.GetAxis("Vertical");
		float steering = maxSteeringAngle * Input.GetAxis("Horizontal");
		
		foreach(AxleInfo axleInfo in axleInfos){
			if(axleInfo.steering){
				axleInfo.leftWheel.steerAngle = steering;
				axleInfo.rightWheel.steerAngle = steering;
			}
			if(axleInfo.motor){
				axleInfo.leftWheel.motorTorque = motor;
				axleInfo.rightWheel.motorTorque = motor;
				
				carCurrentSpeed = (rb.velocity.magnitude * 3.6f) / carMaxSpeed;
			}
			
			ApplyLocalPositionToVisuals(axleInfo.leftWheel);
			ApplyLocalPositionToVisuals(axleInfo.rightWheel);
			
		}
    }
}

[System.Serializable]
public class AxleInfo{
	public WheelCollider leftWheel;
	public WheelCollider rightWheel;
	public bool motor;
	public bool steering;
}

And here is the second:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyCarSound : MonoBehaviour
{
	AudioSource audioSource;
	public float minPitch = 0.05f;
	private float pitchFromCar;
	
    // Start is called before the first frame update
    void Start()
    {
        audioSource = GetComponent<AudioSource>();
		audioSource.pitch = minPitch;
    }

    // Update is called once per frame
    void Update()
    {
		pitchFromCar = MyCarController.cc.carCurrentSpeed;
		if(pitchFromCar < minPitch)
			audioSource.pitch = minPitch;
		else
			audioSource.pitch = pitchFromCar;
    }
}

If you want the complete working files, you can purchase it here:

loading...

Leave a Reply

Your email address will not be published.