Hill Climb Racing Like 2D Car Physics 2 - Add Speed Through Script

It has been some time that I did the first part of this series Hill Climb Racing Like 2D Car Physics 1 - WheelJoint2D, and people were asking me why is it taking so much time to post the second part. Well, it is not easy being an Indie Game Developer you know and it becomes that difficult when you are alone working on writing articles on the blog as well. Never mind, here I am back with the second part as promised.

In this part of the series on How to build a 2D based physics car just like the one which you see in Hill Climb Racing, we will add the capability to apply speed to the wheels via script. Basically it is a post on 2D Car Movement via Script. This post might end with just a single script that we would be adding to the car, but it involves whole sort of Physics understanding. Sit back tight and ride the car!

The Result: Hill Climb Racing Like 2D Car Physics 2 - Add Speed Through Script

If my memory serves me good, we, as of now have a car capable of moving using the motors of the wheelJoints.

Add Friction to the Wheels

The first thing that we would add to the wheels is the friction so that the movement is more crisp and more gripping.

Create a New Folder under the assets in the Project panel and name it as Materials. Right click on the Materials folder and select Physics2DMaterial. Name this as Tires. Set the Friction to 3 and Bounciness to 0.05. Though these are not what it would be in real but, I found these values work quite well to give it a real car ride feel.

Tire Physics2DMaterial
Once you have created the material, apply this material to the CircleCollider2D's Material property of both the wheels.

Add Physics2DMaterial to the CircleCollider2D
Add Drag to the 2D Car

To give the car some realistic effect while moving, it is necessary to add some Linear Drag. You can add the Linear Drag to the Car's RigidBody2D by simply setting the Linear Drag property to 0.1 and set the Angular Drag property to 0.05. You have to do this to the CarBody, RearWheel and FrontWheel.

Add Linear Drag and Angular Drag
WheelJoint2D Motor Configuration

Uncheck the Use Motor property of the WheelJoint2D component connected to the FrontWheel which is just what a real car would work like.

Add Script

Now we will add a script which would add movement to the 2D Car. Create a New Folder named Scripts and add a New C# Script inside this folder. Name the script as WheelJointCarMovement. Attach the script to the CarBody object. Open the script and add the below code to it

using UnityEngine; 
using System.Collections; 

public class WheelJointCarMovement : MonoBehaviour { 
 //reference to the wheel joints
 WheelJoint2D[] wheelJoints; 
 //center of mass of the car
 public Transform centerOfMass;
 //reference tot he motor joint
 JointMotor2D motorBack;  
 //horizontal movement keyboard input
 float dir = 0f; 
 //input for rotation of the car
 float torqueDir = 0f;
 //max fwd speed which the car can move at
 float maxFwdSpeed = -5000;
 //max bwd speed
 float maxBwdSpeed = 2000f;
 //the rate at which the car accelerates
 float accelerationRate = 500;
 //the rate at which car decelerates
 float decelerationRate = -100;
 //how soon the car stops on braking
 float brakeSpeed = 2500f;
 //acceleration due to gravity
 float gravity = 9.81f;
 //angle in which the car is at wrt the ground
 float slope = 0;
 //reference to the wheels
 public Transform rearWheel;
 public Transform frontWheel;

 // Use this for initialization 
 void Start () { 
  //set the center of mass of the car
  rigidbody2D.centerOfMass = centerOfMass.transform.localPosition;
  //get the wheeljoint components
  wheelJoints = gameObject.GetComponents<WheelJoint2D>(); 
  //get the reference to the motor of rear wheels joint
  motorBack = wheelJoints[0].motor; 
 //all physics based assignment done here
 void FixedUpdate(){
  //add ability to rotate the car around its axis
  torqueDir = Input.GetAxis("Horizontal"); 
   rigidbody2D.AddTorque(3*Mathf.PI*torqueDir, ForceMode2D.Force);

  //determine the cars angle wrt the horizontal ground
  slope = transform.localEulerAngles.z;

  //convert the slope values greater than 180 to a negative value so as to add motor speed 
  //based on the slope angle
   slope = slope - 360;
  //horizontal movement input. same as torqueDir. Could have avoided it, but decided to 
  //use it since some of you might want to use the Vertical axis for the torqueDir
  dir = Input.GetAxis("Horizontal"); 

  //explained in the post in detail
  //check if there is any input from the user
   //add speed accordingly
   motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed -(dir*accelerationRate - gravity*Mathf.Sin((slope * Mathf.PI)/180)*80 )*Time.deltaTime, maxFwdSpeed, maxBwdSpeed);
  //if no input and car is moving forward or no input and car is stagnant and is on an inclined plane with negative slope
  if((dir==0 && motorBack.motorSpeed < 0 ) ||(dir==0 && motorBack.motorSpeed==0 && slope < 0)){
   //decelerate the car while adding the speed if the car is on an inclined plane
   motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed - (decelerationRate - gravity*Mathf.Sin((slope * Mathf.PI)/180)*80)*Time.deltaTime, maxFwdSpeed, 0);
  //if no input and car is moving backward or no input and car is stagnant and is on an inclined plane with positive slope
  else if((dir==0 && motorBack.motorSpeed > 0 )||(dir==0 && motorBack.motorSpeed==0 && slope > 0)){
   //decelerate the car while adding the speed if the car is on an inclined plane
   motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed -(-decelerationRate - gravity*Mathf.Sin((slope * Mathf.PI)/180)*80)*Time.deltaTime, 0, maxBwdSpeed);
  //apply brakes to the car
  if (Input.GetKey(KeyCode.Space) && motorBack.motorSpeed > 0){
   motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed - brakeSpeed*Time.deltaTime, 0, maxBwdSpeed); 
  else if(Input.GetKey(KeyCode.Space) && motorBack.motorSpeed < 0){ 
   motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed + brakeSpeed*Time.deltaTime, maxFwdSpeed, 0);
  //connect the motor to the joint
  wheelJoints[0].motor = motorBack; 



This script has been thoroughly commented for your understanding. However, there is one thing which I think I should touch on - The applying of the speed to the motor. There are various conditions that I have considered here while applying the speed to get the desired result, which are listed below:

Line 67 to 75 of the Script

- Check whether there is any input from the user.
- If yes, add the speed to the motor in the range (maxFwdSpeed, maxBwdSpeed). It is opposite to what you expect since the negative value of motor speed moves the car forward.

NOTE: The usage of WheelJoint2D is not the way in which we are using. Actually, the wheelJoints are to be attached to the Wheels themselves and not the car body. However, I find that using this way makes the car more stable. If you want to use the WheelJoint2D's the right way, maybe, you might want to set the Frequency to a very high value of, say, 50+ to make the Car stable. Give it a try. Also, note you might want to change this script accordingly.

- The formula that we are using here apply speed to the car is similar to


i.e., Final Velocity = Initial Velocity + (Acceleration*time)



Hence, we would have an equation which would look like


Where, g is obviously the acceleration due to gravity.
The reason why we have considered the angles and all is, because, we do not want the car to be stagnant on, say, an inclined road where in no input is given by the user and the motor speed would eventually become zero.
You might perhaps say that the Unity's built in Physics should make this work by default. Well. No. It does not because, the WheelJoint2D's motor speed would block the movement of the car. As the speed would be zero, the wheels wouldn't move and hence the car.
I have used this equation and modified it as per requirements and considering the fact that negative speed moves our car forward.
- We have multiplied by speed by certain constant to get a desired acceleration rate so that the car wouldn't look impractical.

Save the Script and return to Unity. Attach this script to the CarBody component. You would notice that the script expects three components. Drag and drop them as in the image below

2D Car Movement Script - Unity
Now, you should be able to test this Physics Based 2D Car capable of moving based on the Users input and doing all sort of things, just like the Car in Hill Climb Racing does.

Check out the third part from the below link,
Hill Climb Racing Like 2D Car Physics 3 - Add Engine Sound

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.


  1. Thanks for this awesome post on 2D Car Physics. I just loved it

  2. Hello, for movement in android ?

  3. Hello , Thanks for this Tutorials !!
    I do this post to end , but i can not Attach this script to the CarBody component .
    the Unity 5 error is :`UnityEngine.Component.rigidbody2D' is obsolete: `Property rigidbody2D has been deprecated. Use GetComponent() instead. (UnityUpgradable)'

    Please Help Me

    1. I've just started programming too, I realised that obsolete just means that the unity API has been updated. In this case they removed the short for getcomponent. What I did was basically create a public variable for Rigidbody2D rb then replace all the rigidbody2D with rb.

  4. my wheel are become disjoint when car jump and come again to path ..and wheels cross the polygon colider of path and wheel sink to path

  5. Your articles is excellent but unfortunately your website​ design is not responsive.

  6. I agree with everyone else, I wasn't quite sure what it was when i first saw it. But after reading this I'm willing to try it! It sounds interesting....
    Geometry Dash Online Toss The Turtle Snake.is

  7. The fats which are observed in Cla Safflower Oil nuts have honestly been verified to be healthful fats The fat that are awful for you are saturated and trans-fats those are the fat that you ought to keep away from like the plague.

  8. Keep in mind that if any item includes Biogenic Xr utilizing a gadget that extends the , you should be run the other way Would this be difficult as well as risky.

  9. I recognise you cherished Biogenic XR having raisins as a kid. What makes them even more acceptable is they can help improve libido and result in arousal.

  10. Shortness of breath, sleep Cla Safflower Oil deprivation, dazedness, sickness, and swooning spells Is ephedra legitimate which contains an audit of distributed logical.

  11. Awesome article Lot's of data to Read...Great Man Keep Posting and redesign to People..Thanks
    Orders NOW

  12. This is a wonderful post.thanks for sharing barkbox store

  13. Your nowadays because Testro T3 there is a secure technique you could use to accomplish that The most secure method endorsed is the one supplied through Size Genetics.

  14. Erectile brokenness in men does not Testx Core really imply that you have a physical hindrance. Mental ineptitude is known as execution.

  15. Through the use of a quality Perlelux pores and skin care regimen consisting of that offered by.

  16. Somogyi Rebound: the ones diabetics Vedda Blood Sugar Remedy who are unable to follow a strict healthy eating plan need to be afflicted by high blood sugar signs within.

  17. <a href=" https://clashroyalhacktool.com/”> Clash Royale online hack</a>
    I was perusing your article and thought about whether you had considered making a digital book on this subject. You're composing would offer it quick. You have a great deal of composing ability.

  18. You expend day by day, you don't likewise CLA Safflower Oil cheat yourself out of indispensable supplements, minerals, and vitamins your body requirements for ideal activities.

  19. Of the already held convictions on CLA Safflower Oil losing The individuals who are looking for better approaches to get in shape successfully have immediately.

  20. An uncommon blend to discover; Dermagen IQ particularly in all the Dermagen IQ for UK compound based hostile to maturing healthy skin items which more often.

  21. I read your Post. Its really helpful post. thanks for write this post.
    Dash Cam Reviews

  22. Yet, in any event on the off chance Dermagen IQ that you recognize what fixings to search for, you'll have a beginning stage In this way, here goes.

  23. Wholesome vitamins application Rapiture Muscle Builder over the long term Tridenosen h Rapiture Muscle for Spain or simply tridenosen, is a famous new product for weight.

  24. Perlelux of their hostile to maturing healthy skin for men. The way to accomplishing solid looking skin are the fixings which men should center around.

  25. D BAL Max Building method for them. Do not forget to alternate the exercises and weight load each one to a few weeks for max efficacy.

  26. Slimfire Forskolin to process and helps with separating any undesirable Forskolin unyielding fat put away in the body.

  27. Xtrfact important to that individual's contribution in your getting medicinal services advantages or installment identified .

  28. Pure CBD Oil To a good diet crusade after good dieting effort, we should consider looking to nature to hit the nail on the head It's sooooo basic.

  29. Dermagen IQ who are presently getting some distance from standard items containing these Dermagen IQ for UK synthetic fixings towards considerably.

  30. Nitridex procedure at the back of natural enhancement At that point, your frame produced unique biochemicals.

  31. Zylix Plus Barrenness is quick turning into a grave medicinal concern around the world. Ladies envious of considering.

  32. Hello admin this was very cool post, i was playing in my cell phone. Native News Live

  33. Fabulous Collection of Fur coats for Woman, Mink Jackets, Chinchilla Coats, Sable Coats and Many More.Click Here:
    Fur coat .

  34. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. best buy nanny cam

  35. Pleasant learning picking up article. This post is truly the best on this significant theme. Movierulz

  36. Awesome data! I as of late ran over your web journal and have been perusing along. I thought I would leave my first remark. I don't realize what to say aside from that I have. APK PRO

  37. I am unquestionably making the most of your site. You certainly have some extraordinary understanding and incredible stories. Visit Fifa 2018 live streaming

  38. Really great post. I just discovered your online journal and needed to say that I have truly delighted in perusing your blog entries. Any way I'll be subscribing to your food and I trust you post again soon. Enormous much obliged for the helpful information.
    Content Management Development

  39. Hi, Rigidbody.centerOfMass does not work in your script. Is there any solution, I am using Unity2017

  40. Are there any side effects?
    Rapid Tone Weight Loss has become increasingly popular as a weight-loss supplement in recent years, and scientists and medical professionals generally support the product’s ability to increase the amount of fat on the body. Coleus Rapid Tone Weight Loss is good for weight loss as it can increase the body’s own fat burning abilities, helping you to lose weight over a prolonged period of time. What’s more, the product doesn’t produce any harmful reactions or side effects. Many of these supplements available on the market today consist of natural ingredients, and when used as part of a healthy lifestyle, can help to produce the desired results.


  41. Luna Trim
    It shields your frame from maladies and different physical trouble. HCA controls the fat aggregation. Luna Trim, this is the motive determined in dropping fats. Since it claims HCA at 60% which finishes the suitable want to work compelling manner. https://supplementch3mistry.wordpress.com/2018/07/08/about-of-luna-trim/


  42. Very Nice Article.! Thanks for sharing this amazing information ..


  43. Pleasant website and completely extraordinary. You can improve yet regardless I say this perfect.Keep striving generally advantageous.
    Quotes About Ignoring Someone You Like


  44. keto trim diet reviews
    Since its’ launch in early 2018, tens of thousands of adults worldwide have successfully lost weight. Keto Trim is on everybody’s tongue and it could be exactly what you need to get slim sexy body for summer.

  45. Pure Fast KetoUnadulterated Fast Keto Fat Burning framework is give you numerous noticeable focal points like I show beneath: It consumes all calorie utilization and fat from the body framework. It controls the development of fat in the body framework. It is exceptionally useful for improving your state of mind the entire day. It is a superb cure that expansion your fat losing limit which is gives you more advantageous life. It smothers your tallness of yearning and dependably enables you to greater. This wonderful thing is powerful for you in consume extra bodyweight rapidly. It upgrades your rest and enables you to encounter simple. This things diminish your everything your pressure and furthermore empowers you to encounter unwind and better.Smooth Curves Forsko lin It consumes all extra fat from the belly and gives a level belly. It enables you to look dazzling and shocking. The astounding Pure Fast Keto Fat Burning enables you to look canny and thin. How It Does Work? Unadulterated Fast Keto Fat Burning amazing dropping bodyweight and fat losing thing is planned from all more beneficial and 100 % natural parts and goes about as defensively on our bodies framework. https://www.smore.com/1ed2f-pure-fast-keto-o-shocking-reviews

  46. Keto Ultra Dietenhance memory: "John Stuart Mill (...) composed power (hemp) to restore recollections of overlooked and inquire about, and regularly revealed to me that smokers impaired to have the capacity to recall the overlooked things." (1) In late decades, researchers and totally disregarded these reports, maybe on the grounds that administration reserves are mostly occupied with the look for the negative impacts of maryjane. In any case, there are many point by point writes about recollections of the best turn off, which appears to be unbelievable that science can disregard Keto Ultra Diet wonder for quite a while. These are only two precedents of reports of pot:Keto X Factor Computer software engineer 19 "McKenzie Cruz" writes in "What I like maryjane" on the site of pot Lester utilized: "It appears that recollections to take my mind rapidly, extremely smooth, and started to recall things from my youth that made me feel exceptionally upbeat and happy. https://www.smore.com/tzemr-keto-ultra-diet-plan-reviews-omg

  47. Thanks for every other informative site. The place else may just I get that kind of information written in such an ideal means? I have a venture that I’m just now operating on, and I have been on the look out for such information. Elia & Ponto

  48. Kinky Lash ExtensionThis angle was familiar with me by my epidermis master. She suggested me its utilization since I was losing my havens and eyelash at a more remarkable speed due to which my noteworthiness was separating. She named creating and debasing as the key clarification behind the shedding of the eyelash and refuges locks. At in any event, I utilized this serum twice each of the a considerable measure of your time and exertion and now, I execute it just once.

    I found the dwelling to execute the serum indispensable. It is eaten up by your epidermis angle agreeably. The viewpoint updated the difference in my eyelash and asylums inside brief time interim of your present and exertion. I think it is the intrigue of the basic fixings in this perspective making execute so sensibly. The new bolts of my wats or wats or sanctuaries and eyelash are more extensive, more focused, incredible and long. This serum gives proper survey of stock to them to make fine. I indicate thankfulness toward it with entire of my heart for getting into my entire lifestyle and enhancing my greatness.
    Read Our Most Rated Bone + oak Forskolin Reviews Weight Loss Supplement https://www.smore.com/tzuyv-bone-oak-forskolin-reviews-scam

  49. PureFit Keto Reviews How would I utilize PureFit Keto DietPro?

    Stage 1 - Take pills

    Take 2 cases of PureFit Keto DietPro twice day by day

    Stage 2 - Start fat consuming

    PureFit Keto Shark Tank Get your fat consuming increasingly digestion

    Stage 3 - Transform Your Body

    Find the energizing outcomes with a level stomach, a firmer butt and lean legs

    For what reason would it be a good idea for you to attempt?


  50. 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 obb


  51. We have to be realistic with reference to Keto Burn Xtreme Diet. These are the bread-and-butter of Keto Burn Xtreme Diet. You could have all the necessities of Keto Burn Xtreme Diet pleasure at this point. That's a fact of life. Consequently, wing it.


  52. keto diet calculator Eventually more insulin gets secreted than is needed and a blood sugar crash results. Your body then snaps into action to get you some sugar and fast! Adrenalin is released to tell the liver to break down some protein into glucose causing the symptoms. Did I say the first step was brutal?

  53. Someone Sometimes with visits your blog regularly and recommended it in my experience to read as well. The way of writing is excellent and also the content is top-notch. Thanks for that insight you provide the readers! Buy Tyres Online

  54. Magnum TRT I was progressively prepared every single when I was using Magnum TRT. I experienced I expanded more imperativeness than an ordinary people. By and by, I am prepared to do my step by step endeavors without having any tiredness by any stretch of the creative energy. I feel better every morning after I wake up till going to rest amid the night. Magnum TRT is just a brilliant inclination ever and I am exceptionally satisfied by my present body wellbeing. An extra preferred standpoint is my working inclinations improved well ordered.

  55. This is because these types of wheels are not just like any other wheels. They are supposed to be unique so that they can speed up the racing car for one to win a race.Best xbox one steering wheel 2019

  56. I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much. newton

  57. I found Hubwit as a transparent s ite, a social hub which is a conglomerate of Buyers and Sellers who are ready to offer online digital consultancy at decent cost. Do you want to change your car tyres? Are you looking to buy car tyres bangalore? Well, TyresNmore is a leading destination for buying tyres online in India with doorstep delivery and tyre fitting service. We have the leading tyre brands at the most competitive price. Keeping utmost customer convenience in mind, Tyresnmore has been designed in a way to make browsing, selecting, buying and fitting tyres seem like an easy task for every owner. With Tyresnmore, customers can save time, money and efforts, providing the best tyres. car tyres bangalore

  58. Need for custom wheels was readily felt in the early years of car manufacturing when consumers realized that investment in automobile is a huge undertaking. Best PS4 Steering Wheels 2019: Buying Guide, Reviews

  59. Alpha XR We do not know if they also make other products or how long they have been in business and these are all things that could help us in forming a better impression about Alpha XR.

  60. Purefit Keto Diet Plan

    Purefit Keto Diet Plan is demonstrated a gift for me. Purefit Keto Diet Plan discharges my pressures with the right usage of the enhancement. within the few days, I began to lose my weight. I simply wanna thank the institution for giving me this enhancement. here is Michal. With the each day time table and having the increase durations of time in sitting inside the place of business I, had the fat gut. Purefit Keto Diet Plan changed into a dishonorable issue for me to have a fats tummy. I truly needed to remove Purefit Keto Diet Plan at any cost. At that factor I came to assume around Purefit Keto Diet Plan. Purefit Keto Diet Plan became verified an enchantment for me.


  61. Given article is very helpful and very useful for my admin, and pardon me permission to share articles here hopefully helped :

    Cara Menyembuhkan Pengeroposan Tulang

  62. This is getting a bit more subjective, but I much prefer the Zune Marketplace. The interface is colorful, has more flair, and some cool features like ‘Mixview’ that let you quickly see related albums, songs, or other users related to what you’re listening to. Clicking on one of those will center on that item, and another set of “neighbors” will come into view, allowing you to navigate around exploring by similar artists, songs, or users. Speaking of users, the Zune “Social” is also great fun, letting you find others with shared tastes and becoming friends with them. You then can listen to a playlist created based on an amalgamation of what all your friends are listening to, which is also enjoyable. Those concerned with privacy will be relieved to know you can prevent the public from seeing your personal listening habits if you so choose.

    Pakistan English news
    Pakistan Breaking news
    Pakistan Latest news
    Pakistan Update news
    Today World news
    Today Pakistan news
    Pakistan Education news
    Technology news
    Pakistan Technology news
    KPK news
    Today KPK news
    Punjab news
    Balochistan news
    Health news
    Science news
    Sport News
    Business news
    Sindh news
    Today sindh news