Step by step creation of a Box2D car/truck with motors and shocks

I am dealing with Box2D car for a long time, but I never published a tutorial about the making of a Box2D car, with working wheels and shocks.

If you want to see some posts about Box2D car you can have a look at two ways to make Box2D cars and create a terrain like the one in Tiny Wings with Flash and Box2D – Adding a car

We are going to build our car in 7 steps, so let’s start from the very beginning:

1 – World creation

In this basic step the environment to set up the simulation is created, and we also add the floor.

There’s nothing you did not already see in this blog, so I’d jump straight to the result…

… and then move on to next step.

2 – Adding the car body

At first, the car will be just a rectangle, so that’s what I am adding:

At lines 32-49 a rectangle is added on the world. Here it is:

Since the world is full of cars made by just one rectangle, it’s time to improve our car design.

3 – Adding car parts

Here comes into play Box2D’s capability of creating complex objects by joining simple primitives into compound objects. You can read the theory behind this at the magic of compound objects with Box2D.

We just added a trunk and an hood to the car body. Look how lines 76-78 add car body, trunk and hood to the same b2Body rather than having their own individual b2Body. That’s how you make compound objects.

Also, the hood (a triangle) is created from a vector of points, in the same way slices are made in slicing, splitting and cutting objects with Box2D – part 2.

Now the car itself is ready.

4 – Adding shocks

To simulate shocks, first we need to create axles. Then wheels will be attached to axles, which will be attached to the car body, with some kind of spring effect.

So, at this time, axles are just a pair of boxes (actually they can have almost any shape, I am using boxes for the sake of simplicity).

Although I just added a couple of boxes, I would like you to see the magic of this step:

Axles and car body do not collide among themselves because they all have the same groupIndex (lines 41, 56, 71 and 89).

You can find the theory behind groupIndex at Introducing Box2D filtering.

5 – Adding wheels

In the same way I added axles, I am adding wheels. All in all, they are just two circles with the same groupIndex as the rest of the car parts.

And here is our car:

Now, it’s time to use joints to connect single car parts and motors to bring them to life:

6 – Attaching wheels to axles

Most of the new code in this script is used to manage keyboard interaction. Now with LEFT and RIGHT arrow keys you can make wheels “run”.

Anyway, the interesting thing lies in the use of revolute joints (theory: Box2D joints: Revolute Joint) to attach the wheels to axles and motors (theory: Box2D joints: Revolute Joint – Building motors) to make wheels move.

maxMotorTorque property defines the maximum motor torque used to achieve the desired motor speed, while SetMotorSpeed method sets the motor speed in radians per second.

Press LEFT and RIGHT arrow keys to make wheels roll. Now, the last step.

7 – Attaching axles to car body

We will use prismatic joints to attach axles to the car. You can find the theory at Box2D joints: Prismatic Joints.

Prismatic joints can act like springs if you play with their motor properties. You will find how to create your custom car after this final result:

Here shocks bounce a lot because I wanted to show your how does everything work.

Customize your car

Here is a list of parameters you can change to create your custom car:

Car mass: modifying the density of the car body, the trunk and the hood (lines 45, 60 and 75) you will change the car mass, its weight and eventually its center of gravity if you make (example) an heavy trunk and a light hood.

Axles position: can be changed at lines 101 and 105. Normally a long distance between front and rear axle makes the car more stable.

Wheels radius: can be changed at line 110.

Wheels motor torque: you can change it at lines 134 and 140. The higher the torque, the lower the time to bring wheels to desired speed.

Wheels speed: at lines 200-201 you can set the speed of the wheels.

Shocks orientation: at lines 150 and 153 you can change shocks orientation. It’s the last argument.

Shocks excursion: changing lines 145-146 will affect prismatic joints upper and lower limits, modifying shocks excursion.

Shocks feedback: shocks motor speed and max force (just like wheels speed and max torque) are updated at lines 202-205 in real time at every frame to simulate the spring effect.

Download the source code.

Can you find a good mix of these parameters to create a well responsive car?

  • Woow! Really nice work Emanuele. many many thanks…

  • Very nice tutorial.

    Will you show us how to ‘skin’ the car? I.e. give it a look based on bitmaps?


  • Eric

    Jes Fink-Jensen:
    Skinning is a lot easier than you think, you just add the sprites somewhere on the stage and each frame just get the position of each object, convert the coordinates to pixels and move the sprites.

    And actually Emanuele already did a tutorial with sprites using box2d:

  • i like this article well good!!!

  • Nice,
    but just for know, does Box2D applies gravity and physics only in a 2D world view for the side,
    or is it possible to apply mass changes into a world seen from above?.

  • iapapa28

    Hello, Emanuele.
    I’m not sure how to contact you, but I could really use some help regarding a problem (unrelated to this article) I encountered while developing a game. Can I send you a mail or something? Cheers.

  • Emanuele Feronato

    @eidern: you can simulate a 2D world seen from above if you set the gravity to b2Vec2(0,0)

    @iapapa28: you can mail me at info[at], but unfortunately I am not able to give help to individual projects. Anyway, should your problem be VERY interesting, I will be happy to post it on the blog

  • lucian


  • Pingback: Step by step creation of a Box2D car/truck with motors and shocks – Emanuele Feronato « priyadarshansalkar()

  • Pingback: Cool Stuff with the Flash Platform - 8/30/2011 | Remote Synthesis()

  • Dhivakar

    Hi Emanuel,

    I am currently developing a car game. It is a 2D side Scrolling game. In my game the car moves on top of the created path(Box), i am also having triangular paths. so when i try to move my car over the triangle, after reaching the top of the triangle the car overturns. as i fixed my max speed allowed is very low the car is working fine over the triangular Paths. but i need to increase the speed for my game play. can u help me how to solve this problem?

  • this car behaves strange :)

  • coldstar

    Can you tell me which version of the Box2D you have used in this game? It’s not 2.1a? Thanks!

  • Charles

    I have created two different projects with JBox 2d and can not get the ‘step’ method to change any positions. After all my frustration I wrote this stub that still will not change positions of an object. Am I missing something? or do I need to just give up on ‘J’box2d???…………
    package com.HelloBox;

    import org.jbox2d.collision.AABB;
    import org.jbox2d.collision.CircleDef;
    import org.jbox2d.collision.PolygonDef;
    import org.jbox2d.common.Vec2;
    import org.jbox2d.dynamics.Body;
    import org.jbox2d.dynamics.BodyDef;
    import org.jbox2d.dynamics.World;
    import org.jbox2d.dynamics.joints.*;

    import android.os.Bundle;
    import android.util.Log;

    public class HelloBox extends Activity {
    PhysicsWorld mWorld;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
    mWorld = new PhysicsWorld();
    Log.v(“called worldStart”, “NOw”);


    public class PhysicsWorld {

    public int targetFPS = 60;
    public int timeStep = (1 / targetFPS);
    public int iterations = 6;
    private Body[] body = new Body[1];

    private BodyDef groundBodyDef;
    private PolygonDef groundShapeDef;

    boolean doSleep = true;
    Vec2 gravity = new Vec2((float) 0.0, (float) -10.0);
    Vec2 sposition = new Vec2((float) 10.0, (float) 10.0);
    public AABB worldAABB = new AABB();
    World world = new World(worldAABB, gravity, doSleep);

    public void worldStart() {
    worldAABB = new AABB();
    worldAABB.lowerBound.set(new Vec2((float) -100.0, (float) -100.0));
    worldAABB.upperBound.set(new Vec2((float) 100.0, (float) 100.0));
    // Step 2: Create Physics World with Gravity
    Vec2 gravity = new Vec2((float) 0.0, (float) -10.0);
    boolean doSleep = true;
    world = new World(worldAABB, gravity, doSleep);

    // Step 3: Create Ground Box

    groundBodyDef = new BodyDef();
    groundBodyDef.position.set(new Vec2((float) 0.0, (float) -10.0));
    Body groundBody = world.createBody(groundBodyDef);
    groundShapeDef = new PolygonDef();
    groundShapeDef.setAsBox((float) 50.0, (float) 10.0);
    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set((float)0.0, (float) 0.0);
    body[0] = world.createBody(bodyDef);
    CircleDef circle = new CircleDef();
    circle.radius = (float) 0.8;
    circle.density = (float) 1.0;

    // Assign shape to Body

    for (int i = 0; i < 60; ++i) {
    world.step(timeStep, iterations);
    Vec2 position = body[0].getPosition();
    float angle = body[0].getAngle();
    Log.v("Physics Test", "Pos: (" + position.x + ", " + position.y + "), Angle: " + angle + "COUNT " + i );


  • Muhammad Faisal Aleem


    I found your post very helpful. I have successfully made a truck car in box2d-cocos2d and deployed it on iphone. The only problem I am facing is the speed control. When i increase speed of car the car starts to go up with the speed increase. How I can keep the car on ground with a certain speed limit? Any help would be appreciated.

  • Pingback: Modeling a Car in Android | Giga thoughts ...()

  • Bellisima!
    I am getting my first real exposure to Box2D via Lua and Löve, and this is very helpful! Thank you!

  • Sabarulla


    If apply torque to bike body using left and right keys. But it is rotating infinite times pls help me

  • Jack

    Yes, it is very nice car.

    But I cannot figure how to make it stay on the ground.
    I have tried constraining, and playing with values. I also tried the advanced car tutorial with the axle, but this one has a problem, which is the vehicle is too slow to stop and change direction.