Two ways to make Box2D cars

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import Box2D.Collision.*;// bounding box of our world
import Box2D.Common.Math.*;// for vector(define gravity)
import Box2D.Dynamics.*;// define bodies and define world
import Box2D.Dynamics.Joints.*;
import Box2D.Collision.Shapes.*;// define our shapes
import flash.display.*;// sprite class
 
const MAX_STEER_ANGLE:Number = Math.PI/3;
const STEER_SPEED = 1.5;
const SIDEWAYS_FRICTION_FORCE:Number = 10;
const HORSEPOWERS:Number = 40
const CAR_STARTING_POS:b2Vec2 = new b2Vec2(10,10);
 
const leftRearWheelPosition:b2Vec2 = new b2Vec2(-1.5,1.90);
const rightRearWheelPosition:b2Vec2 = new b2Vec2(1.5,1.9);
const leftFrontWheelPosition:b2Vec2 = new b2Vec2(-1.5,-1.9);
const rightFrontWheelPosition:b2Vec2 = new b2Vec2(1.5,-1.9);
 
var engineSpeed:Number =0;
var steeringAngle:Number = 0
 
var myWorld:b2World;
 
var worldBox:b2AABB = new b2AABB();
worldBox.lowerBound.Set(-100,-100);
worldBox.upperBound.Set(100,100);
 
myWorld = new b2World(worldBox, new b2Vec2(0,0) , true);
 
//Create some static stuff
var staticDef = new b2BodyDef();
staticDef.position.Set(5,20);
var staticBox = new b2PolygonDef();
staticBox.SetAsBox(5,5);
myWorld.CreateBody(staticDef).CreateShape(staticBox);
staticDef.position.x = 25;
myWorld.CreateBody(staticDef).CreateShape(staticBox);
staticDef.position.Set(15, 24);
myWorld.CreateBody(staticDef).CreateShape(staticBox);
 
 
// define our body
var bodyDef:b2BodyDef = new b2BodyDef();
bodyDef.linearDamping = 1;
bodyDef.angularDamping = 1;
bodyDef.position = CAR_STARTING_POS.Copy()
 
var body:b2Body = myWorld.CreateBody(bodyDef);
body.SetMassFromShapes();
 
var leftWheelDef:b2BodyDef = new b2BodyDef();
leftWheelDef.position = CAR_STARTING_POS.Copy();
leftWheelDef.position.Add(leftFrontWheelPosition);
var leftWheel:b2Body = myWorld.CreateBody(leftWheelDef);
 
var rightWheelDef:b2BodyDef = new b2BodyDef();
rightWheelDef.position = CAR_STARTING_POS.Copy();
rightWheelDef.position.Add(rightFrontWheelPosition);
var rightWheel:b2Body = myWorld.CreateBody(rightWheelDef);
 
var leftRearWheelDef:b2BodyDef = new b2BodyDef();
leftRearWheelDef.position = CAR_STARTING_POS.Copy();
leftRearWheelDef.position.Add(leftRearWheelPosition);
var leftRearWheel:b2Body = myWorld.CreateBody(leftRearWheelDef);
 
var rightRearWheelDef:b2BodyDef = new b2BodyDef();
rightRearWheelDef.position = CAR_STARTING_POS.Copy();
rightRearWheelDef.position.Add(rightRearWheelPosition);
var rightRearWheel:b2Body = myWorld.CreateBody(rightRearWheelDef);
 
// define our shapes
var boxDef:b2PolygonDef = new b2PolygonDef();
boxDef.SetAsBox(1.5,2.5);
boxDef.density = 1;
body.CreateShape(boxDef);
 
//Left Wheel shape
var leftWheelShapeDef = new b2PolygonDef();
leftWheelShapeDef.SetAsBox(0.2,0.5);
leftWheelShapeDef.density = 1;
leftWheel.CreateShape(leftWheelShapeDef);
 
//Right Wheel shape
var rightWheelShapeDef = new b2PolygonDef();
rightWheelShapeDef.SetAsBox(0.2,0.5);
rightWheelShapeDef.density = 1;
rightWheel.CreateShape(rightWheelShapeDef);
 
//Left Wheel shape
var leftRearWheelShapeDef = new b2PolygonDef();
leftRearWheelShapeDef.SetAsBox(0.2,0.5);
leftRearWheelShapeDef.density = 1;
leftRearWheel.CreateShape(leftRearWheelShapeDef);
 
//Right Wheel shape
var rightRearWheelShapeDef = new b2PolygonDef();
rightRearWheelShapeDef.SetAsBox(0.2,0.5);
rightRearWheelShapeDef.density = 1;
rightRearWheel.CreateShape(rightRearWheelShapeDef);
 
body.SetMassFromShapes();
leftWheel.SetMassFromShapes();
rightWheel.SetMassFromShapes();
leftRearWheel.SetMassFromShapes();
rightRearWheel.SetMassFromShapes();
 
var leftJointDef:b2RevoluteJointDef = new b2RevoluteJointDef();
leftJointDef.Initialize(body, leftWheel, leftWheel.GetWorldCenter());
leftJointDef.enableMotor = true;
leftJointDef.maxMotorTorque = 100;
 
var rightJointDef = new b2RevoluteJointDef();
rightJointDef.Initialize(body, rightWheel, rightWheel.GetWorldCenter());
rightJointDef.enableMotor = true;
rightJointDef.maxMotorTorque = 100;
 
var leftJoint:b2RevoluteJoint = b2RevoluteJoint(myWorld.CreateJoint(leftJointDef));
var rightJoint:b2RevoluteJoint = b2RevoluteJoint(myWorld.CreateJoint(rightJointDef));
 
var leftRearJointDef:b2PrismaticJointDef = new b2PrismaticJointDef();
leftRearJointDef.Initialize(body, leftRearWheel, leftRearWheel.GetWorldCenter(), new b2Vec2(1,0));
leftRearJointDef.enableLimit = true;
leftRearJointDef.lowerTranslation = leftRearJointDef.upperTranslation = 0;
 
var rightRearJointDef:b2PrismaticJointDef = new b2PrismaticJointDef();
rightRearJointDef.Initialize(body, rightRearWheel, rightRearWheel.GetWorldCenter(), new b2Vec2(1,0));
rightRearJointDef.enableLimit = true;
rightRearJointDef.lowerTranslation = rightRearJointDef.upperTranslation = 0;
 
myWorld.CreateJoint(leftRearJointDef);
myWorld.CreateJoint(rightRearJointDef);
 
 
// debug draw
var dbgDraw:b2DebugDraw = new b2DebugDraw();
dbgDraw.m_sprite = new Sprite();
addChild(dbgDraw.m_sprite);
dbgDraw.m_drawScale = 20.0;
dbgDraw.m_fillAlpha = 0.3;
dbgDraw.m_lineThickness = 1.0;
dbgDraw.m_drawFlags = b2DebugDraw.e_shapeBit |b2DebugDraw.e_centerOfMassBit;
myWorld.SetDebugDraw(dbgDraw);
 
 
//========== FUNCTIONS ==========
 
//This function applies a "friction" in a direction orthogonal to the body's axis.
function killOrthogonalVelocity(targetBody:b2Body){
	var localPoint = new b2Vec2(0,0);
	var velocity:b2Vec2 = targetBody.GetLinearVelocityFromLocalPoint(localPoint);
 
	var sidewaysAxis = targetBody.GetXForm().R.col2.Copy();
	sidewaysAxis.Multiply(b2Math.b2Dot(velocity,sidewaysAxis))
 
	targetBody.SetLinearVelocity(sidewaysAxis);//targetBody.GetWorldPoint(localPoint));
}
 
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed_handler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased_handler);
 
function keyPressed_handler(e:KeyboardEvent) {
	if(e.keyCode == Keyboard.UP){
		body.WakeUp();
		engineSpeed = -HORSEPOWERS;
	}
	if(e.keyCode == Keyboard.DOWN){
		engineSpeed = HORSEPOWERS;
	}
	if(e.keyCode == Keyboard.RIGHT){
		steeringAngle = MAX_STEER_ANGLE
	}
	if(e.keyCode == Keyboard.LEFT){
		steeringAngle = -MAX_STEER_ANGLE
	}
}
 
function keyReleased_handler(e:KeyboardEvent){
	if(e.keyCode == Keyboard.UP || e.keyCode == Keyboard.DOWN){
		engineSpeed = 0;
	} 
	if(e.keyCode == Keyboard.LEFT || e.keyCode == Keyboard.RIGHT){
		steeringAngle = 0;
	}
}
 
addEventListener(Event.ENTER_FRAME, Update, false, 0 , true);
 
function Update(e:Event):void {
	myWorld.Step(1/30, 8);
	killOrthogonalVelocity(leftWheel);
	killOrthogonalVelocity(rightWheel);
	killOrthogonalVelocity(leftRearWheel);
	killOrthogonalVelocity(rightRearWheel);
 
	//Driving
	var ldirection = leftWheel.GetXForm().R.col2.Copy();
	ldirection.Multiply(engineSpeed);
	var rdirection = rightWheel.GetXForm().R.col2.Copy()
	rdirection.Multiply(engineSpeed);
	leftWheel.ApplyForce(ldirection, leftWheel.GetPosition());
	rightWheel.ApplyForce(rdirection, rightWheel.GetPosition());
 
	//Steering
	var mspeed:Number;
	mspeed = steeringAngle - leftJoint.GetJointAngle();
	leftJoint.SetMotorSpeed(mspeed * STEER_SPEED);
	mspeed = steeringAngle - rightJoint.GetJointAngle();
	rightJoint.SetMotorSpeed(mspeed * STEER_SPEED);
}

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package {
 
   import flash.display.Sprite;
   import flash.events.Event;
 
   import Box2D.Dynamics.*;
   import Box2D.Collision.*;
   import Box2D.Collision.Shapes.*;
   import Box2D.Common.Math.*;
   import Box2D.Dynamics.Joints.*;
 
   public class TruckGame extends Sprite {
 
      public const ITERATIONS      : int       = 30;
      public const TIME_STEP       : Number    = 1.0/60.0;
      public const SCREEN_WIDTH    : int       = 800;
      public const SCREEN_HEIGHT   : int      = 500;
      public const DRAW_SCALE      : Number   = 50;
 
      private var world    : b2World;
      private var cart    : b2Body;
      private var wheel1    : b2Body;
      private var wheel2    : b2Body;
      private var axle1   : b2Body;
      private var axle2   : b2Body;
      private var motor1   : b2RevoluteJoint;
      private var motor2   : b2RevoluteJoint;
      private var spring1   : b2PrismaticJoint;
      private var spring2   : b2PrismaticJoint;
 
      private var screen   : Sprite;
      private var input   : Input;
 
 
      public function TruckGame() : void {
 
         // create the drawing screen //
         screen = new Sprite();
         screen.scaleY = -1;
         screen.y = SCREEN_HEIGHT;
         addChild(screen);
 
         // initialize input object //
         input = new Input(this);
 
         // add main loop event listener //
         addEventListener(Event.ENTER_FRAME, update, false, 0, true);
 
         init();
 
      }
 
      private function init() : void {
 
         // create world //
         var worldAABB:b2AABB = new b2AABB();
 
         worldAABB.lowerBound.Set(-200, -100);
         worldAABB.upperBound.Set(200, 200);
 
         world = new b2World(worldAABB, new b2Vec2(0, -10.0), true);
 
 
         // allow debug drawing //
         var debugDraw : b2DebugDraw = new b2DebugDraw();
         debugDraw.m_sprite          = screen;
         debugDraw.m_drawScale       = DRAW_SCALE;
         debugDraw.m_fillAlpha       = 0.1;
         debugDraw.m_lineThickness    = 2.0;
         debugDraw.m_drawFlags       = 1;
 
         world.SetDebugDraw(debugDraw);
 
 
         // temporary variables for adding new bodies //
         var i               : int;
         var body             : b2Body;
         var bodyDef          : b2BodyDef;
         var boxDef             : b2PolygonDef;
         var circleDef          : b2CircleDef;
         var revoluteJointDef   : b2RevoluteJointDef;
         var prismaticJointDef   : b2PrismaticJointDef;
 
 
         // add the ground //
         bodyDef = new b2BodyDef();
         bodyDef.position.Set(0, 0.5);
 
         boxDef = new b2PolygonDef();
         boxDef.SetAsBox(50, 0.5);
         boxDef.friction = 1;
         boxDef.density = 0; 
 
         body = world.CreateBody(bodyDef);
         body.CreateShape(boxDef);
 
         boxDef.SetAsOrientedBox(1, 2, new b2Vec2(-50, 0.5), 0);
         body.CreateShape(boxDef);
 
         boxDef.SetAsOrientedBox(1, 2, new b2Vec2(50, 0.5), 0);
         body.CreateShape(boxDef);
 
         boxDef.SetAsOrientedBox(3, 0.5, new b2Vec2(5, 1.5), Math.PI/4);
         body.CreateShape(boxDef);
 
         boxDef.SetAsOrientedBox(3, 0.5, new b2Vec2(3.5, 1), Math.PI/8);
         body.CreateShape(boxDef);
 
         boxDef.SetAsOrientedBox(3, 0.5, new b2Vec2(9, 1.5), -Math.PI/4);
         body.CreateShape(boxDef);
 
         boxDef.SetAsOrientedBox(3, 0.5, new b2Vec2(10.5, 1), -Math.PI/8);
         body.CreateShape(boxDef);
 
         body.SetMassFromShapes();
 
 
         // add random shit //
         circleDef = new b2CircleDef();
         circleDef.density = 0.01;
         circleDef.friction = 0.1;
         circleDef.restitution = 0.5;
 
         for (i = 0; i < 30; i++) {
            circleDef.radius = Math.random()/20+0.02;
 
            bodyDef = new b2BodyDef();
            bodyDef.position.Set(Math.random()*35+15, 1);
            bodyDef.allowSleep = true;
            bodyDef.linearDamping = 0.1;
            bodyDef.angularDamping = 0.1;
 
            body = world.CreateBody(bodyDef);
 
            body.CreateShape(circleDef);
            body.SetMassFromShapes();
         }
 
 
         // add cart //
         bodyDef = new b2BodyDef();
         bodyDef.position.Set(0, 3.5);
 
         cart = world.CreateBody(bodyDef);
 
         boxDef = new b2PolygonDef();
         boxDef.density = 2;
         boxDef.friction = 0.5;
         boxDef.restitution = 0.2;
         boxDef.filter.groupIndex = -1;
 
         boxDef.SetAsBox(1.5, 0.3);
         cart.CreateShape(boxDef);
 
         boxDef.SetAsOrientedBox(0.4, 0.15, new b2Vec2(-1, -0.3), Math.PI/3);
         cart.CreateShape(boxDef);
 
         boxDef.SetAsOrientedBox(0.4, 0.15, new b2Vec2(1, -0.3), -Math.PI/3);
         cart.CreateShape(boxDef);
 
         cart.SetMassFromShapes();
 
         boxDef.density = 1;
 
 
         // add the axles //
         axle1 = world.CreateBody(bodyDef);
 
         boxDef.SetAsOrientedBox(0.4, 0.1, new b2Vec2(-1 - 0.6*Math.cos(Math.PI/3), -0.3 - 0.6*Math.sin(Math.PI/3)), Math.PI/3);
         axle1.CreateShape(boxDef);
         axle1.SetMassFromShapes();
 
         prismaticJointDef = new b2PrismaticJointDef();
         prismaticJointDef.Initialize(cart, axle1, axle1.GetWorldCenter(), new b2Vec2(Math.cos(Math.PI/3), Math.sin(Math.PI/3)));
         prismaticJointDef.lowerTranslation = -0.3;
         prismaticJointDef.upperTranslation = 0.5;
         prismaticJointDef.enableLimit = true;
         prismaticJointDef.enableMotor = true;
 
         spring1 = world.CreateJoint(prismaticJointDef) as b2PrismaticJoint;
 
 
         axle2 = world.CreateBody(bodyDef);
 
         boxDef.SetAsOrientedBox(0.4, 0.1, new b2Vec2(1 + 0.6*Math.cos(-Math.PI/3), -0.3 + 0.6*Math.sin(-Math.PI/3)), -Math.PI/3);
         axle2.CreateShape(boxDef);
         axle2.SetMassFromShapes();
 
         prismaticJointDef.Initialize(cart, axle2, axle2.GetWorldCenter(), new b2Vec2(-Math.cos(Math.PI/3), Math.sin(Math.PI/3)));
 
         spring2 = world.CreateJoint(prismaticJointDef) as b2PrismaticJoint;
 
 
         // add wheels //
         circleDef.radius = 0.7;
         circleDef.density = 0.1;
         circleDef.friction = 5;
         circleDef.restitution = 0.2;
         circleDef.filter.groupIndex = -1;
 
         for (i = 0; i < 2; i++) {
 
            bodyDef = new b2BodyDef();
            if (i == 0) bodyDef.position.Set(axle1.GetWorldCenter().x - 0.3*Math.cos(Math.PI/3), axle1.GetWorldCenter().y - 0.3*Math.sin(Math.PI/3));
            else bodyDef.position.Set(axle2.GetWorldCenter().x + 0.3*Math.cos(-Math.PI/3), axle2.GetWorldCenter().y + 0.3*Math.sin(-Math.PI/3));
            bodyDef.allowSleep = false;
 
            if (i == 0) wheel1 = world.CreateBody(bodyDef);
            else wheel2 = world.CreateBody(bodyDef);
 
            (i == 0 ? wheel1 : wheel2).CreateShape(circleDef);
            (i == 0 ? wheel1 : wheel2).SetMassFromShapes();
 
         }
 
 
         // add joints //
         revoluteJointDef = new b2RevoluteJointDef();
         revoluteJointDef.enableMotor = true;
 
         revoluteJointDef.Initialize(axle1, wheel1, wheel1.GetWorldCenter());
         motor1 = world.CreateJoint(revoluteJointDef) as b2RevoluteJoint;
 
         revoluteJointDef.Initialize(axle2, wheel2, wheel2.GetWorldCenter());
         motor2 = world.CreateJoint(revoluteJointDef) as b2RevoluteJoint;
 
      }
 
 
      public function update(e : Event) : void {
 
         if (input.isPressed(32)) {
            world = null;
            init();
            return;
         }
 
         motor1.SetMotorSpeed(15*Math.PI * (input.isPressed(40) ? 1 : input.isPressed(38) ? -1 : 0));
         motor1.SetMaxMotorTorque(input.isPressed(40) || input.isPressed(38) ? 17 : 0.5);
 
         motor2.SetMotorSpeed(15*Math.PI * (input.isPressed(40) ? 1 : input.isPressed(38) ? -1 : 0));
         motor2.SetMaxMotorTorque(input.isPressed(40) || input.isPressed(38) ? 12 : 0.5);
 
         spring1.SetMaxMotorForce(30+Math.abs(800*Math.pow(spring1.GetJointTranslation(), 2)));
         //spring1.SetMotorSpeed(-4*Math.pow(spring1.GetJointTranslation(), 1));
         spring1.SetMotorSpeed((spring1.GetMotorSpeed() - 10*spring1.GetJointTranslation())*0.4);         
 
         spring2.SetMaxMotorForce(20+Math.abs(800*Math.pow(spring2.GetJointTranslation(), 2)));
         spring2.SetMotorSpeed(-4*Math.pow(spring2.GetJointTranslation(), 1));
 
         cart.ApplyTorque(30*(input.isPressed(37) ? 1: input.isPressed(39) ? -1 : 0));
 
         screen.x -= (screen.x - (-DRAW_SCALE*cart.GetWorldCenter().x + SCREEN_WIDTH/2 - cart.GetLinearVelocity().x*10))/3;
         screen.y -= (screen.y - (DRAW_SCALE*cart.GetWorldCenter().y + 2*SCREEN_HEIGHT/3 + cart.GetLinearVelocity().y*6))/3;
 
         world.Step(TIME_STEP, ITERATIONS);
 
         FRateLimiter.limitFrame(60);
 
      }
 
   }
 
}

Follow the official thread here.

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (42 votes, average: 4.90 out of 5)
Loading ... Loading ...
Flash Templates provided by Template Monster are pre-made web design products developed using Flash technology.
They can be easily customized to meet the unique requirements of your project.
Be my fan on Facebook and follow me on Twitter! Exclusive content for my Facebook fans and Twitter followers

This post has 48 comments

  1. Bruno

    on April 6, 2009 at 2:48 pm

    Simple and Perfect! Thanks Emanuele, i search this entire last week!

  2. Eliott Robson

    on April 6, 2009 at 7:21 pm

    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?

  3. Monkios

    on April 6, 2009 at 7:37 pm

    Pretty neat.

  4. Brian Yamabe

    on April 6, 2009 at 9:38 pm

    Awesome, I have an idea for a top-down auto game and had no idea where to start. Thanks!

  5. Rasheed

    on April 6, 2009 at 10:04 pm

    Very cool examples! Can’t wait to see some more.

  6. Xitri

    on April 6, 2009 at 10:13 pm

    In the first example the car moves as though in water. The centre of rotation at the car is exposed on the centre? I tried to do such, the truth not with Box2D, and the centre of rotation of the car put between back wheels: http://xitri.com/2008/07/09/flash-programming-drive-a-car.html

  7. Houen

    on April 7, 2009 at 10:40 am

    Great post, emanuele!

  8. Peter

    on April 7, 2009 at 6:19 pm

    :o :o Awesomeeeeeeeee… I searched for this for a while ago but gave up, now I found it xD

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

    on April 9, 2009 at 11:20 am

    [...] Two ways to make Box2D cars : Emanuele Feronato – [...]

  10. reyco1

    on April 12, 2009 at 9:38 pm

    Hey… why is the y scale -1 in the second example? The values look so small also..

  11. dVyper

    on April 27, 2009 at 4:44 pm

    These examples are absolutely amazing! Good work :)

  12. bogdan

    on October 28, 2009 at 10:24 am

    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
    thanks!
    you’re awesome!

  13. Xorox

    on February 4, 2010 at 2:35 pm

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

  14. T

    on March 12, 2010 at 2:36 pm

    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!

  15. eanjo

    on March 19, 2010 at 5:23 am

    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?

  16. saravanan

    on April 5, 2010 at 6:59 am

    Hi guys second tutorial not working how said its awesome

  17. saravanan

    on April 5, 2010 at 7:01 am

    please explain how to use this code pls give zip format help me

  18. Rodrigo

    on April 6, 2010 at 1:08 am

    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?

    Rod

  19. drobs

    on April 6, 2010 at 3:57 pm

    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.

    drobs

  20. Physics Test

    on April 25, 2010 at 2:37 am

    [...] The engine comes with the ability to use a a flash physics engine called Box2D, which can do some really cool shit. I made it my mission to learn how to do [...]

  21. Rodrigo

    on May 17, 2010 at 3:53 am

    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?

  22. Indy

    on June 29, 2010 at 12:24 am

    Hi,

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

    Regards

    i

  23. Indy

    on August 17, 2010 at 1:47 am

    Hi,

    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?

    Regards

    i

  24. Mike

    on August 24, 2010 at 7:33 am

    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!

  25. Mike

    on August 25, 2010 at 5:32 am

    Does any body know what my errors are? (read comment above) I’m in Flash CS5 running Box2d 2.0.2

  26. Randomman159

    on September 11, 2010 at 7:20 am

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

  27. vikram

    on October 28, 2010 at 8:08 am

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

  28. lacas82

    on October 31, 2010 at 8:30 pm

    How to do this lines in java?:

    var sidewaysAxis = targetBody.GetXForm().R.col2.Copy();
    sidewaysAxis.Multiply(b2Math.b2Dot(velocity,sidewaysAxis))

    Theres is nothing R.col2 in there…

  29. Cocos2d Box2d Car | Applausible Blog

    on November 23, 2010 at 11:22 pm

    [...] ported this Emanuele Feronato Flash ActionScript example to Cocos2d for the [...]

  30. Ron Rejwan

    on December 29, 2010 at 7:13 pm

    Hi great work!

    Quick question, in order to synchronize this simulation over network, which variables do I need to send over to my clients? :)

  31. corporalik

    on January 13, 2011 at 12:51 am

    Hi,
    please, is there a simplified version of top-down car? this sample is too hard for newbie.
    Thanks in advance

  32. Drakon - place ยป Box2D bike

    on January 22, 2011 at 2:10 pm

    [...] I have found some nice tutorial of making old style bike game with box2d physics engine. It was made in flash version of it by Emanuele Feronato [...]

  33. iAN

    on February 16, 2011 at 8:08 pm

    GetXForm() is replaced by GetTransform() in 2.1a

  34. Woodrobot

    on February 17, 2011 at 11:50 pm

    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.

  35. NEVENA ALEKSIEVA

    on March 19, 2011 at 2:20 pm

    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

  36. NEVENA ALEKSIEVA

    on March 19, 2011 at 4:37 pm

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

  37. Philippe

    on March 20, 2011 at 7:20 pm

    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).
    Thanks,
    Philippe

  38. Philippe

    on March 21, 2011 at 2:27 pm

    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.
    Thanks,
    Philippe

  39. Bob

    on March 26, 2011 at 3:38 pm

    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.

  40. aitken85

    on April 7, 2011 at 5:35 am

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

    spring2.SetMaxMotorForce(...);
    spring2.SetMotorSpeed(...);

    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.

  41. Couch Multiplayer | Emotely Blog

    on April 28, 2011 at 8:19 pm

    [...] codenamed 3D API for Flash Player and Adobe AIR).    Physics/Collision [11] Two Ways to make Box2d Cars This entry was posted in Uncategorized. Bookmark the [...]

  42. Leo

    on June 26, 2011 at 10:52 pm

    Great Grat tutorial Emanuele. Stavo cercando di contattarti tramite email ma non funziona il bottone contact.

    Ciao

  43. Muhammad

    on August 1, 2011 at 6:33 am

    very interesting, we can rock in flash.

  44. Hardik

    on August 15, 2011 at 9:20 am

    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

  45. Silver Moon

    on October 6, 2011 at 5:13 am

    Hello

    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 ?

    Regards
    Silver

  46. Sohan

    on November 3, 2011 at 7:36 am

    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( );
    (Spring1)->SetMotorSpeed();

    (Spring2)->SetMaxMotorForce( );
    (Spring2)->SetMotorSpeed();

    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!

  47. Dhivakar

    on November 15, 2011 at 2:20 pm

    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?

  48. davidp

    on January 24, 2012 at 2:02 pm

    thanks, very useful tutorial :)