Hill Climb Racing Like 2D Car Physics 1 - WheelJoint2D

Some days back I was going through some of the features of Unity 2D, and I bumped into this very neat feature called Joint2D. There are five Joint2D's, of which I was particularly interested in this so called WheelJoint2D. I went through the manual provided by the Unity's official website and I felt there was a need to write a post on exactly how could one use this WheelJoint2D.

The Result: Hill Climb Racing Like 2D Car Physics 




Right, in this post we will see how to use this WheelJoint2D to build a physics based 2D car, a side view 2D car, in fact. This was also requested by one of our users, to write a post on How to build a Physics based 2D car in the sideview. The person had not mentioned that we use a WheelJoint2D for that, but yeah, he neither mentioned that we should not use this (*wink*)

If you want to follow along, Create a new project in 2D mode, save the scene by pressing ctrl+s and give it a meaningful name. Or any scene in a 2D mode would do. Convert the scene into 2D, if it already isn't.

Download the 2D Car and Road sprites from this link and copy the folder into your project. Make sure they are imported as Sprites and not as textures. Also, change the import settings to get the best quality sprites possible.
You can follow the gif below if you are not aware of how to do these two tasks:

Sprite Import Settings
Also make sure you set the CarBody's Pixel To Units to 60.

Road Setup

Add the road sprite by simply dragging it from the Sprites folder under the Assets and dropping it in the Hierarchy. This would create a road object for you.

Position it at (0, 0, 0).  Set the Scale to (10, 3, 1).

Add a PolygonCollider2D to the road object. This would help us drive our Car to be built, run on it. (Change the Max Size of the road sprite to 4096, if the image is blurry. Edit the collider if you need to by clicking on the Edit Collider button.
Note that you need remove the existing PolygonCollider2D component and add it again after you change the import settings, as it would be more precise.)

Road Setup

Background Setup

Change the color of the Camera's Background to a somewhat light blue color so as to give the effect of a sky.

Camera Background

Car Setup

Create an Empty GameObject and name it as Car. Position it at (-240, 5, 0).

Adding Car Body

Drag the CarBody sprite onto your scene i.e., drop it into the Hierarchy under the empty gameobject you just created. This would make the CarBody sprite, the child of Car object. Add a Rigidbody2D component to it, change the Mass to 3. Also add a PolygonCollider2D. If you are using Unity 4.5 and on-wards, the collider generated should be accurate enough to carry on with this post. If not modify the collider to fit the CarBody by clicking on the Edit Collider button.

Car Body Setup

Add Wheels

Add the Wheel sprite inside the Car object as well. Add a Rigidbody2D component to this wheel. Also add a CircleCollider2D. Duplicate this wheel object by pressing ctrl+d while it is selected in the Hierarchy. If not, right click on wheel and select Duplicate.
Rename these wheels as FrontWheel and RearWheel. Position the RearWheel at (-2.7, -1.2, 0). Set the Position of the FrontWheel to (3.38, -1.2, 0).
Now, your 2D Car should look something like:

2D Car Setup

Add WheelJoint2D component

Add two WheelJoint2D component to the CarBody object. Check the Collide Connected checkbox. In the Connected Rigid Body field drag and drop the RearWheel. Repeat this for the other wheel joint, and yes, you would drag the other wheel, which is, the FrontWheel into the Connected Rigid Body of the wheel joint.
Also, check the Use Motor checkbox (this can be done via script, but. I mean, well, chuck it and check it *wink*) of both the wheel joint components for us to be able to use the motor, and in turn, control the movement of the car.

Give the car, the ability to absorb shock

Set the values of Anchors and Connected Anchors of both the wheel joints as in the image below:

WheelJoint2D Setup

If you are using a different set of sprites, maybe you want to use a different values. But, in general you would want to set the Anchors (Blue Ring in the image abovesomewhere near the lower end of the wheels and the Connected Anchors (Blue Circle in the image above) at the center of the wheel.

Once you are done with that, you would have a Car which has the ability to absorb shocks, all hail the suspension component of the wheel joints.

Car's Center of Mass

I'm not quite sure of what would the center of mass of the CarBody sprite would be, as I have not had good experiences with the default CoM provided by unity. Maybe it could be because of the PolygonCollider2d, but I would rather be safe than sorry. So we would simply add an empty gameobject named CenterOfMass and position it wherever we need the CoM to be and later we assign this empty gameobject's position to the CoM of the Rigidbody2D.

Create an empty gameobject. Make it child of the Car object and name it as CenterOfMass. Position it at (0, -0.2, 0).

Center Of Mass


Camera Setup and Car Follow

Create a new C# Script named SmoothFollow2D and add the below code to it
using UnityEngine;
using System.Collections;

public class SmoothFollow2D : MonoBehaviour {

 private Vector3 velocity = Vector3.zero;
 public Transform target;
 
 // Update is called once per frame
 void Update () 
 {
  if (target)
  {
   Vector3 point = camera.WorldToViewportPoint(target.position);
   Vector3 delta = target.position - camera.ViewportToWorldPoint(new Vector3(0.2f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
   Vector3 destination = transform.position + delta;
   transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, 0);
  }
  
 }
}

Save the script and return to Unity. Attach this script to the Main Camera. Drag and drop the CarBody object in the Target field of the SmoothFollow2D script component. Set the Size of the Camera component to 10.

Camera Setup

Now, we have set everything up. We will test our progress. This can be done simply pressing the
Play button or use the shortcut ctrl+p.
The Car just falls on the road and nothing happens apart from that. This is because the Motor Speed is set to 0. Change the Motor Speed and the Car will start to move.

2D Car Physics - Unity WheelJoint2D

In the next post, we will see how to control the speed of this motor via script.

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


See you around.

Share on Google+

About Sujit Horakeri

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.
Connect with him on:
    Blogger
    Facebook

11 comments:

  1. Nice tutorial. Hopefully you can explain how to properly motor the WheelJoint2D by code or explain how to set up some other joint to give the realistic forward and reverse force that "Hill Climb Racing" has. So far, the answer has been to add force to the vehicle body which creates a downward force and is opposite from this realism most are wanting. The vehicle needs to "lurch up", and grip down with the wheels just as a normal vehicle does. Thanks again, looking forward to the next part. Waiting patiently.

    ReplyDelete
    Replies
    1. Hi.. I apologize for the extremely late reply. But yeah, I hope you understand. I'm kind of tensed by the expectations :P
      Nevertheless, the negative motor speed is because its a work around for wheels with a smaller radius.
      The thing is the wheeljoint2d is made to be attached to the wheel and not the car body, like I have in the post.
      If you have to use it the way it is supposed to be, which is attaching the joints to wheels. The wheels would wobble around the suspensions and to get over this drawback you might want to increase the suspension frequency. GIVE IT A TRY.
      The other problem is the wheeljoint itself is very flawed at the moment or it could be that I don't know, in fact most of the unity community doesn't know, how to use it. So I'm trying my best to get this right.

      Delete
    2. Nice tutorial man.. Loved the second part especially.. Quite realistic 2d physics... Hoping to see more such articles.. Maybe you could post an article on adding sound to the car engine?

      Delete
  2. what if i want to make the car move by buttons like hill climb racing ?

    ReplyDelete
  3. ok the tutorial was great now i have problem using the game in android,actually with the controls. please tell me how to get the dir and the torquedir in the android input button as we dont have input.getaxis(horizontal);
    and please dont tell me the input.touch method, it would be better if u can tell me the new ui button method

    ReplyDelete
  4. Hey, I need to ask you if we can use the scripts as commercial use?

    Please get back to me when you can! Thanks very much and nice tutorial :)

    ReplyDelete
  5. Very nice tutorial but I have a problem.And the problems is how to add button with dir and torqueDir.Please make a tutorial about this.

    ReplyDelete
  6. can you please give movement
    script for android

    ReplyDelete
  7. Look at no less than 10 distinct autos that fall inside your value run before settling on a choice. Take a companion or relative who is proficient about autos to take a gander at them and test drive every auto. They will see things that may some way or another be missed by you or an auto purchasing learner. dodge dealership in south carolina

    ReplyDelete
  8. If you plan on using your bike on mountain trails then you do need a mountain bike. If you do plan on racing on both the street and on mountain trails you can consider getting another set of wheels made for the street. These wheels would be narrower and have a slick tread.motorcycle shipping

    ReplyDelete