Build 10 games and learn game development along the way in this fast paced game development course

Get the source code of 12 commercial games, loaded 50+ million times, and learn the secrets of game design

Learn how to make a successful Flash game from a real world example. Fully commented source code

Create realistic Flash physics games from scratch with advanced features, from Angry Birds to Crush the Castle

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?

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (19 votes, average: 4.74 out of 5)
Loading ... Loading ...
Learn how to make a successful commercial Flash game from a real world example: get the fully commented source code of Globez, a Flash game played millions of times which generated a four figure income. Limited copies available.

Get it now
Be my fan on Facebook and follow me on Twitter! Exclusive content for my Facebook fans and Twitter followers

This post has 18 comments

  1. Yildiray

    on August 22, 2011 at 5:30 pm

    Woow! Really nice work Emanuele. many many thanks…

  2. Jes Fink-Jensen

    on August 22, 2011 at 5:46 pm

    Very nice tutorial.

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

    Cheers!

  3. Eric

    on August 23, 2011 at 9:36 am

    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:
    http://www.emanueleferonato.com/2009/02/18/a-smart-way-to-manage-sleeping-objects-with-box2d/

  4. hogan scarpe

    on August 23, 2011 at 9:44 am

    i like this article well good!!!

  5. Eidern

    on August 23, 2011 at 1:36 pm

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

  6. iapapa28

    on August 24, 2011 at 10:54 am

    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.

  7. Emanuele Feronato

    on August 24, 2011 at 7:15 pm

    @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]emanueleferonato.com, 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

  8. lucian

    on August 25, 2011 at 7:30 pm

    Nice!

  9. Step by step creation of a Box2D car/truck with motors and shocks – Emanuele Feronato « priyadarshansalkar

    on August 27, 2011 at 9:11 pm

    […] Step by step creation of a Box2D car/truck with motors and shocks – Emanuele Feronato. Share this:TwitterFacebookLike this:LikeBe the first to like this post. Categories Uncategorized […]

  10. Cool Stuff with the Flash Platform - 8/30/2011 | Remote Synthesis

    on September 1, 2011 at 4:43 pm

    […] Feronato continues from an earlier tutorial on creating a Box2D car/truck by adding a motor and shocks to his car. He also expands upon his tutorial series for creating a […]

  11. Dhivakar

    on November 15, 2011 at 2:32 pm

    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?

  12. andy

    on December 16, 2011 at 6:13 pm

    this car behaves strange :)

  13. coldstar

    on December 29, 2011 at 5:13 am

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

  14. Charles

    on January 29, 2012 at 6:24 am

    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.app.Activity;
    import android.os.Bundle;
    import android.util.Log;

    public class HelloBox extends Activity {
    PhysicsWorld mWorld;

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

    setContentView(R.layout.main);
    }

    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);
    groundBody.createShape(groundShapeDef);
    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
    body[0].createShape(circle);
    body[0].setMassFromShapes();

    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 );
    }

    }
    }
    }

  15. Muhammad Faisal Aleem

    on November 12, 2012 at 10:36 am

    Hi,

    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.

  16. Modeling a Car in Android | Giga thoughts ...

    on June 19, 2013 at 2:57 pm

    […] AndEngine & Box2D physics.  This post is based on a great blog post by Emanuele Feronato on “Step by step creation of a Box2D car/truck with motors and shocks”. So getting down to the “nuts & bolts” of  creating a car we need to create 3 […]

  17. Martin

    on July 11, 2013 at 8:12 am

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

  18. Sabarulla

    on August 30, 2013 at 1:29 pm

    Hey

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

Thank you for the download!!

I hope you will find it useful and make something interesting out of it

To keep up to date with the blog, why don't you like my Facebook page and follow me on Twitter?

Want to learn more? Don't miss this:

Learn how to make a successful commercial Flash game from a real world example: get the fully commented source code of Globez, a Flash game played millions of times which generated a four figure income. Limited copies available.

Get it now

×