# 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.

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

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");
if(torqueDir!=0){
}
else{
}

//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
if(slope>=180)
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
if(dir!=0)
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

vf=vi+at

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

Now,

a=gsinθ

Hence, we would have an equation which would look like

vf=vi+gsinθt

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.

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

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)'

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. how we repeat Background

6. Thanks!!! awesome tutorial.

8. How to repeat the background?

9. How to repeat the background?

10. good tutorial

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

12. 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

13. 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.
http://www.drozhealthblog.com/cla-safflower-oil/

14. 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.
http://www.healthprograme.com/biogenic-xr-reviews/

15. 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.
http://xtrfact.com/biogenic-xr-uk/

16. Shortness of breath, sleep Cla Safflower Oil deprivation, dazedness, sickness, and swooning spells Is ephedra legitimate which contains an audit of distributed logical.
http://www.drozhealthblog.com/cla-safflower-oil/

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

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

19. 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.
http://www.drozhealthblog.com/testro-t3-uk/

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

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

22. 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.
http://www.drozhealthblog.com/vedda-blood-sugar-remedy/

23. <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.

24. 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.
http://xtrfact.com/cla-safflower-oil/

25. 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.
http://xtrfact.com/cla-safflower-oil/

26. 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.

Dash Cam Reviews

28. 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.
http://www.drozhealthblog.com/dermagen-iq/

29. 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.
http://xtrfact.com/rapiture-muscle-builder/

30. 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.
http://www.drozhelp.com/perlelux/

31. 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.
http://xtrfact.com/d-bal-max-review/

32. Slimfire Forskolin to process and helps with separating any undesirable Forskolin unyielding fat put away in the body.
http://supplementdigestdog.com/slimfire-forskolin/

33. Xtrfact important to that individual's contribution in your getting medicinal services advantages or installment identified .
http://xtrfact.com/

34. 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.
http://www.drozhealthblog.com/pure-cbd-oil/

35. Dermagen IQ who are presently getting some distance from standard items containing these Dermagen IQ for UK synthetic fixings towards considerably.
http://www.drozhealthblog.com/dermagen-iq/

36. Nitridex procedure at the back of natural enhancement At that point, your frame produced unique biochemicals.
http://supplementdigestdog.com/nitridex/

37. Zylix Plus Barrenness is quick turning into a grave medicinal concern around the world. Ladies envious of considering.
http://www.drozhealthblog.com/zylix-plus/

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

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

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

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

42. 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

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

44. 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

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

46. 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.

https://supplementch3mistry.wordpress.com/2018/06/27/rapid-tone-diet/

47. great post thanks for sharing news

48. 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/

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

https://sherrill-furniture-review

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

51. Hello , Thanks for this Tutorials !!
AlphaIndians

52. 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.
http://www.cureidea.com/keto-trim-diet-reviews/

https://www.smore.com/j286r-smooth-curves-forskolin-o-reviews

54. 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

55. 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

56. 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.
https://www.smore.com/wmg3b-kinky-lash-vs-false-eyelashes
Read Our Most Rated Bone + oak Forskolin Reviews Weight Loss Supplement https://www.smore.com/tzuyv-bone-oak-forskolin-reviews-scam

57. 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?

58. 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

59. 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.

https://www.lasambucalifestyle.com/keto-burn-xtreme/
https://www.smore.com/kuj7m-keto-burn-xtreme-free-trial-pack

60. 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?
https://www.smore.com/e0jgk-keto-ultra-diet-reviews-shark-tank

61. 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

62. 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.