Hill Climb Racing Like 2D Car Physics 3 - Add Engine Sound

In the first two posts of this series where in we are creating a Hill Climb Racing Game like 2D car physics in a side view, we learned, how to create a physically stable 2D Car and added the functionality of controlling it via C# script. In this post we will add engine sound effect to our 2D Car.

The first thing you need to do is to attach an Audio Source to the CarBody object. To do this simply select the CarBody in the Hierarchy and click on Add Component and search Audio Source. In case you are wondering what is an Audio Source and what does it do?

Audio Source, as the name suggests is the source which generates Audio. You need to have an Audio Listener in your scene as well, which, obviously would listen to the Audio. By default, you will have an Audio Listener attached to your Main Camera. In case, you have deleted the Main Camera and added another camera, do add Audio Listener component to it.

This Audio Source attached to the CarBody would expect you to give it an Audio Clip which is to be played. Download this engine sound Audio Clip ( or you can add your own made engine sound clip as well ) and add it to the the Audio Clip field of the audio source.

Audio Listener attached to Main Camera

Audio Source attached to CarBody

Create a New C# Script under the Scripts folder and name it as EngineSound. Attach this script to the CarBody object. Open the script and add the below code to it:

using UnityEngine;
using System.Collections;

public class EngineSound : MonoBehaviour {
 //audiosource reference
 private AudioSource carSound;
 
 //the range for audio source pitch
 private const float lowPtich = 0.5f;
 private const float highPitch = 5f;

 //change the reductionFactor to 0.1f if you are using the rigidbody velocity as parameter to determine the pitch
 private const float reductionFactor = .001f;

 //Rigidbody2D carRigidbody;
 private float userInput;
 //wheeljoint2d reference
 WheelJoint2D wj;
 
 void Awake ()
 {
                //get the Audio Source component attached to the car
                carSound = GetComponent<AudioSource>();
  //get the wheelJoint2D component attached to the car
  wj = GetComponent<WheelJoint2D>();
  //carRigidbody = GetComponent<Rigidbody2D>();
 }
 
 void FixedUpdate()
 {
  //get the userInput
  userInput = Input.GetAxis("Horizontal");
  //get the absolute value of jointSpeed
  float forwardSpeed =Mathf.Abs(wj.jointSpeed);
  //float forwardSpeed = transform.InverseTransformDirection(carRigidbody.velocity).x;
  //calculate the pitch factor which will be added to the audio source
  float pitchFactor = Mathf.Abs (forwardSpeed * reductionFactor * userInput) ;
  //clamp the calculated pitch factor between lowPitch and highPitch
  carSound.pitch = Mathf.Clamp (pitchFactor, lowPtich, highPitch);
 }
 
}

Save the script and return to Unity and test the scene. On doing so, you would notice that the car engine has an idle engine sound. On pressing the left or right arrow keys, you would notice that the car has a nice acceleration sound which increases as the speed increases. And obviously it will be clamped to the highPitch and lowPitch values.

There is one more thing you would have noticed while testing the scene, the pitch of the audio moves back to the idle engine sound after a fraction of a second when you do not press the keys anymore. It is just like what happens in reality, you accelerate and the engine makes sound. If you remove your foot from the acceleration pedal, it doesn't make that sound anymore.

This is all we had in this post. I'm not sure if I would be posting anymore posts in this series, but yeah I'll see you around.

Share on Google+

About Unknown

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
    Blogger
    Facebook

44 comments:

  1. Hey, how to convert getaxis to new UI mobile button? thank you

    ReplyDelete
    Replies
    1. You can add a button and add a Pointer Down event to that button.. You can define a class variable to store the input value and modify it in your Pointer down event method..

      To add the event follow below steps:
      1. At the bottom of the inspector, click Add
      Component.
      2. Choose Event -> Event Trigger .
      3. Add New Event Type to choose a custom
      event.
      4. The event you want is called Pointer Down.

      Write a method for the pointer down as per your requirements where you change the input values from 1 to 0 and a similar function on holding the brake button where in the value would vary from 0 to -1...

      Delete
    2. Form the mobile mechanic Phoenix, AZ you can get the arrangement of your are vehicle care and its redesigning issue, this individual is a bargain a wide range of vehicle administrations which is used for enumerating your vehicle. So on the off chance that you need to fabricate your vehicle excessively flawless and help its execution by upgrading its element than this individual will propose you the better exhort.

      Delete
  2. Hey Sujit. Nice to work on your tutorial. It was so good until I added WheelJointCarMovement.cs to the car body. As soon as I run the editor the car goes flip forward gradually. I have done your tutorial in Unity 5.0.3 free version. Do I need to tweak the script as the unity physics engine has been changed since the launch of Unity 5. Please let me know. Eager to fix this. Thank you

    ReplyDelete
  3. Sujit you are awesome, nice tutorial i have completed successfully.

    ReplyDelete
  4. It is important to pull the entryway board and after that unclip the two clasps and afterward embed the new auto speaker into the space that is given. It is critical to choose the auto speaker that will be of the same size as the past auto speaker.go to my site

    ReplyDelete
  5. When playing this game you will take care of your own farm. In order to advance to higher levels you will need to plant and harvest crops, invite friends to join you and hire workers to help you with the farm. This is a fun game for those who want to be farmers but live in the city. Taruhan Online

    ReplyDelete
  6. Despite the twisted nature of this game, it can be quite humorous when Crypto goes on rampages, along with creating hysteria among citizens, harassed cows, destroys buildings using his saucer, as well as battling government agents trying to stop Crypto. Bandar sakong

    ReplyDelete
  7. When you purchase a car subwoofer, there are four factors that you have to take into consideration: system power, subwoofer enclosure, available space and crossovers. 15 inch subwoofer

    ReplyDelete
  8. it is easy to look for high-quality SOUNDEXPERTS.ORG/BEST-6x9-SPEAKERS systems regardless of whether it is for replacement purposes or just to have your current program upgraded.

    ReplyDelete
  9. To take web based amusements from these stimulation menus we need to confront some basic inquiries. Each parent is especially strained about their youngsters' obsessiveness for PC gaming and web based gaming.https://eunblocked.com/run-3/

    ReplyDelete
  10. I think the admin of this web page is really working hard in support of his web page, as here every material is quality based stuff.
    Football Games io Games Unblocked Games

    ReplyDelete
  11. Regardless of all this, there are certain special considerations that people need to seriously look into in ensuring that they have the best sound system to suit their needs.AmplifierExperts

    ReplyDelete
  12. Surround sound systems use the study for psychoacoustics which is the way people perceive and hear sound through the human ears. read more at audiogeekhub.com

    ReplyDelete
  13. In either case you are risking damage to the stereo, dash, or other equipment behind the dash. This can cause more expense than the Stereo originally cost in repair bills.Remote Car Starter Akron

    ReplyDelete
  14. A sign of the measure of sound that will leave your speakers on its getting a flag is dictated by its affectability rating. soundexperts

    ReplyDelete
  15. There are numerous top notch sound speakers accessible in the market today.Acura Tire PSI

    ReplyDelete
  16. This is cool post and i enjoy to read this post. your blog is fantastic and you have good staff in your blog. nice sharing keep it up. http://ampleom.postagon.com/546f2enzn

    ReplyDelete
  17. Obviously there is no compelling reason to toss the infant out with the shower water! https://www.uberafricaforum.com/uber-philadelphia-office/

    ReplyDelete
  18. Administration expert is one other term, which we use to allude to an automobile mechanic. Mohammad Amani

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. Extraordinary things you've generally imparted to us. Simply continue written work this sort of posts.The time which was squandered in going for educational cost now it can be utilized for studies.Thanks hail damage car repair denver

    ReplyDelete
  21. Wouldn't it be incredible in the event that you could locate a straightforward method to book business car enlist or a car for your occasions from your own particular home?Advantage Car & Truck Rental

    ReplyDelete
  22. I truly welcome this superb post that you have accommodated us. I guarantee this would be valuable for the vast majority of the general population. hail damage car repair

    ReplyDelete
  23. It will also let you know if any of the airbags have been deployed, if the vehicle has been re-salvaged at all, and the previous odometer reading as well. namcar

    ReplyDelete
  24. wow, great, I was wondering how to cure acne naturally. and found your site by google, learned a lot, now i’m a bit clear. I’ve bookmark your site and also add rss. keep us updated.car rental under 21 Miami

    ReplyDelete
  25. Today, I was just browsing along and came upon your blog. Just wanted to say good blog and this article helped me a lot, due to which I have found exactly I was looking. mechanic mobile service tampa

    ReplyDelete
  26. There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game. Both boys and girls feel the impact of just a moment?s pleasure, for the rest of their lives.
    Hill Climb Racing 2 hack

    ReplyDelete
  27. The article on this site is very interesting, thank you
    SPESIAL PROMO AWAL TAHUN..!!!
    Depo 20K Free T-Shirt Exclusive dari Lenovo Poker..
    Bandar Judi
    Bandar Ceme
    Bandar Poker
    Login Poker
    Situs Poker
    Dominoqq

    ReplyDelete
  28. Thank you for taking the time to publish this information very useful! mp3 download

    ReplyDelete
  29. A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up Toronto Party Bus

    ReplyDelete
  30. A lot of people having an incorrect image about the cash advance loans or sometimes refer it as bad credit payday loans. Niagara Falls Wedding Limo

    ReplyDelete
  31. One present why galore businesses opt for postcards is because they are overmuch cheaper to be prefab and this can forbear a lot of expenses on the lengthened run.  Oakville Party Bus

    ReplyDelete
  32. On the Craigslist page, explore to your area's page, at that point click Cars and Trucks by Owner. private car sales

    ReplyDelete
  33. I value the blog article.Really thank you! Keep writing. Links Locksmith

    ReplyDelete
  34. This particular papers fabulous, and My spouse and i enjoy each of the perform that you have placed into this. I’m sure that you will be making a really useful place. I has been additionally pleased. Good perform! alquiler de carros

    ReplyDelete
  35. Im no expert, but I believe you just made an excellent point. You certainly fully understand what youre speaking about, and I can truly get behind that. Wedding Limo Oakville

    ReplyDelete
  36. 10 Best Turntables Under $1000 Reviews and Guide 2019. January 27, 2019 by Mark Warren Leave a Comment. This 2019, the time has come to put your records on! In the event that you haven't found the brilliant universe of vinyl yet, this is the ideal opportunity to encounter why it is well-adored by many! Put resources into a top notch turntable for a sentimental li Best Turntables Under $300 Reviews

    ReplyDelete