Have fun and help me to get to 1,000,000 downloads!

Two ways to make Box2D cars

Emanuele Feronato Box2D, Flash, Game design

I am showing you two ways to make cars with Box2d, with source codes included

These are examples I found on the web – I will make my ones later – you can find interesting in order to make cars using Box2D.

Top Down Car Simulation

Making a top down game in Box2D is not that different than making a side view game… you just don’t have to set gravity.

Here it is a top-down racing game

And this is the script to handle it

more information at the official forum thread

Truck car game

This is a truck car game, this concept was very popular a couple of years ago.

The truck is made using various joints, such as revolute joints and prismatic joints.

Here it is the source code:

Follow the official thread here.

From null to full HTML5 cross platform game

I will take you by hand from the bare bones of JavaScript programming through the creation of a full cross platform HTML5 game, with detailed explainations and source code.

If you don't know where to start, then From null to full HTML5 cross platform game is the book for you.

Comments 70

  1. Eliott Robson

    WOW, Always wanted to know how to do this! How would i go about using images rather than squares so i could design a motorbike or something?

  2. Pingback: Bookmarks for April 9th from 09:00 to 09:00 « what i say // jon burger

  3. bogdan

    Hi ,
    in the truck game demo you have the add wheel function and you set there wheel1.
    the question is how do I reset the wheel1.angle?

    If I use wheel1.GetAngle I can only see it but can’t set it and if I try with wheel1.angle=0; or wheel1.rotation=0; doens’t work.. please help
    you’re awesome!

  4. Xorox

    Hi Emanuel, great example, as always.. i have a question, how would you introduce a handbrake to your topview car simulation ?

  5. T

    great examples! I was wondering if you could make an updated version for the new 2.1a version of Box2d – as it looks like GetXForm (and xforms altogether) are now gone from the library!

  6. eanjo

    Nice tutorial.
    But when i copy the source code, i cant run it,
    here’s the error I’ve recieve:

    1046: Type was not found or was not a compile-time constant: Input.

    1180: Call to a possibly undefined method Input.

    1120: Access of undefined property FRateLimiter.

    I don’t know that input variable.;-(

    can any one knows this case?
    and what if i want my movieclip to be the image on stage?

  7. Rodrigo

    Hey Emanuele. I’m hacing trouble understanding this code:
    spring1.SetMaxMotorForce(30+Math.abs(800*Math.pow(spring1.GetJointTranslation(), 2)));
    spring1.SetMotorSpeed((spring1.GetMotorSpeed() – 10 * spring1.GetJointTranslation()) * (5)/Constantes.RATIO);
    spring2.SetMaxMotorForce(30+Math.abs(800*Math.pow(spring2.GetJointTranslation(), 2)));
    spring2.SetMotorSpeed( -4 * Math.pow(spring2.GetJointTranslation(), 1));

    I changed the density of my car and the torque applied to the wheels… and they started dancing all over the place when going to fast. Any ideas?


  8. drobs

    very nice tutorial, has helped alot, but I also have the same problem as eanjo.
    have been looking around the web for a few days now and just can’t find it ..

    so if someone could help me out, it would be greatly appreciated.


  9. Pingback: Physics Test

  10. Rodrigo

    I don’t think I’m doing this right. I took the topdown simulation and created a new project on FlashDevelop. It worked like a charm, except for one thing: The car dances all over the place. I mean, really.. I steer left and accelerate, and it goes like right and starts spinning arround the main body’s mass center.

    I think the problem is in killOrthogonalVelocity. Any ideas?

  11. Indy


    Great tutorial. Any advice on how you would handle allowing the car to skid a little on different frictional surfaces?



  12. Indy


    Looking at the side car with 2 wheels, I dont see anything in the code which makes the axles appear as they do. i.e. they appear to be 2 shapes per axel, with one cylinder moving inside another cylinder? All I can see in the code is one rectangle formed as an oriented box – per axle.

    Any ideas?



  13. Mike

    I’m getting the same issues as eanjo.

    1046: Type was not found or was not a compile-time constant: Input.
    1180: Call to a possibly undefined method Input.
    1120: Access of undefined property FRateLimiter.

    Any body know how to fix this. Thanks!

    1. Randomman159

      I am also getting these errors, and i went through half a dozen different versions of Box2d. The one with the least errors were the Box2d 2.0.*, so basically what you are using. To get rid of the errors i just removed the FRateLimiter line of code, and replaced all the ‘input’ with a class i made, but you could simply have boolean values for whether keys are pressed, and check those booleans (instead of checking through a class).

  14. vikram

    Really Nice Emanuele! Your tutorials are really helpful for the freshers who want to enter into the gaming field. I am a live example for this. Actually I learned a lot from your tutorials. Your tutorials made me win my first interview.

    I have a small problem now! I am creating a dirt bike type game. I created the bike and some platforms. I created a bridge. When the bike is moving on the bridge, it just going into the bridge after traveling through 2 links.

    I don’t know why it is happening. Can you please help me out!

    Thanks in advance…..

  15. lacas82

    How to do this lines in java?:

    var sidewaysAxis = targetBody.GetXForm().R.col2.Copy();

    Theres is nothing R.col2 in there…

  16. Pingback: Cocos2d Box2d Car | Applausible Blog

  17. Pingback: Drakon - place » Box2D bike

  18. Woodrobot

    A great starting point! The side view truck game is great!
    There are not a lot of articles on skinning and matching scaling, but I have figured it out.
    I have added editable vehicles and track and am working on scoring and sound. Lots of fun.
    The prismatic joints sure are finicky and the whole update camera using velocity thing never worked out for me, so I used the location of the vehicle as my offset for all layers. Torque had to be increased to 50 to get over the big hills and make actual jumps and if you put a tall skinny rectangle at each end of the main body rectangle it will not end up on it’s back as much.


    Hi Emanuele, great tutorials, I’m an actionscript developer and I’m doing my masters degree at the moment. We have an asignment (coursework) with the original Box2d engine (written in C++), so I decided to use the second example as part of the coursework, rewrote it from AS3 to C++, used the testbed and it does not look right, axles are not fitting within the cart properly, I could email an snapshot if it will help. Thanks


      ps – I know it has to do with flash coordinate system being upsidedown, do I then have to scale all graphics.y with -1?

  20. Philippe

    Hello Emanuele,
    First thanks for all the good work.
    I just posted an updated version of the top-down car you had made with version 2 on the box2d forum,
    the car does not move!
    I guess I just forgot something essential, but I don’t see what?
    Would you please have a try.
    (source code is for flashdevelop, should be easy to compile and run),
    then please feel free to use it for an update of this post.
    (I’m using this to drive a car inside a flat 3d environment).

    1. Philippe

      Found solution,
      I had forgotten the fact you said that dynamic bodydefs have to be declared as such explicitely, (type=b2Body.b2_dynamicBody).
      I have posted the corrected working code on the Box2D forum thread.

  21. Bob

    Hello dear friend.I have this mistake;
    1046: Type was not found or was not a compile-time constant: Input.
    Help me please.Regards Bob.

  22. aitken85

    In the update function, what do the numbers represent that are passed into these two methods:


    My car must be a lot heavier, as your current values don’t allow my “springs” to push back up. Just wondering if there’s easy way to find out what values I should use instead trial-and-error x1000.

    Cheer, Chris.

  23. Pingback: Couch Multiplayer | Emotely Blog

  24. Hardik

    Hello Sir
    Thanks for such a good post.
    I want the same thing but in cocos2d with box2d.I dont want to use flash.
    Can you help me with the same working model

  25. Silver Moon


    I have few questions , regarding the first example of a car :

    1. Why does the car stop moving when up/down button is released. Since ApplyForce is being used , isnt he car supposed to keep moving once its starts moving ?

    2. What is keeping the wheels attached to the car. When car gains speed , the wheels dont hang out of the car, how is this being done ?


  26. Sohan

    great tutorial,

    I have ported this code in iphone,but my wheels are not moving when I accelerate.

    if I remove the lines

    (Spring1)->SetMaxMotorForce( );

    (Spring2)->SetMaxMotorForce( );

    it works,but not as smooth as it runs here,can you tell me where I am going wrong and what are actually these parameters effects.

    Thanks In Advance!

  27. Dhivakar

    Hi Emananuel,

    Ur work here is amazing, in the second example the truck goes upside down when i cross the obstacles. do u have any idea how to have a truck or a car in 2D side scrolling game which doesn’t go upside down when it cross an obstacle?

  28. Eliya


    My work web security is warning me that your site contains malicious code. This happened on my blog as well, you should check your site to make sure you haven’t been hacked, and install a security plugin.

  29. Davina

    Hi Emananuel,

    I’m having a problem… What box2d version is this tutorial using? Because the version I am using doesn’t have b2XForm… What’s the alternative in the newer version?

    Thank you.

  30. Pingback: 2D Bilspel i Android (hjälp gärna till att färdigställa)

  31. Shekhar Suman

    Does anybody know what does this line do…

    var sidewaysAxis = targetBody.GetXForm().R.col2.Copy();

    Please Help!!

    btw Great Tutorial.

  32. Pingback: Top-Down Car using libGDX and Box2D » Level 1 Gamer

  33. PDM

    Hi emmanuele,

    I’m using Box2d 2.1a and I made a side view car using techniques in this post.
    Everything looks fine, but when it comes to applying torque to the car some problems occur.

    * it takes too long to start spinning and when it spins , can’t stop.
    (there is no setMassFromShapes() function in Box2D 2.1a, I wonder whether this could be the problem)

    * when I use the world.clearForces() the car doesn’t spin at all.

    please help me to solve this problem emmanuele!

  34. Pingback: Introduction to Box2D Physics Engine | Surya's Blog

  35. Pingback: [2D??] ??????box2d??????????? - ??????? - ?????

  36. Pingback: Flash Game Development Inter-web mash up: April 14, 2009 « 8bitrocket.com

  37. Marius

    i want to make a sideviewed racing game in javascript and canvas. your second tutorial is basically what i want to do but in javascript. it would be an nice base for me so what do i have to do to convert your actionscript in javascript to use it with box2dweb? im not familiar with actionscript. my main problem is the typecast at spring1. Hope you can help me.

    PS: Sorry for my bad English.

  38. Vaughan

    Thanks so much, superb example and exactly what we’re after…in Nape though. Do you have any recommendations of how to do this using Nape – have tried everything but can’t quite map this example to its joints. Or perhaps you might do a Nape example sometime :)

  39. Pingback: Box2d c++ can't see b2PolygonShape | DL-UAT

  40. Pingback: Hill Climb Racing - Deconstructed - Car, controls, camera, coins and fuel cans - All sorts of development

  41. Nancy

    So, your tutorials are great. One thing I absolutely stuck on. I am blown away by how I can’t figure this out.

    I made a structure that looks like an equal sign. Two bodies, exact same size with a single prismatic joint that pushes up the top one, like a spring. The top body floats above it, but i cannot, for the life of me, figure out how to narrow the distance between the objects. There is no ‘length’ parameter for prismatic joint.

    I tried positioning the top body lower in space. (it just gets pushed up)
    I tried making it weigh more. (it just increases in density until it breaks through the ground)
    I tried changing the settings on the prismatic joint, translation, angles, limits, everything.

    I made the object out of your car tutorial.

  42. Pingback: Box2d c++ can't see b2PolygonShape | Question and Answer

Leave a Reply

Your email address will not be published. Required fields are marked *