Top Down Car Simulation (Demo & Code)

Hi all

This thread has been extremely helpful- thanks for sharing this code...

I'm wondering if anyone has code related to using the b2TensorDampingController for tire friction... I'm new to Box2D, so I'm not completely sure how to implement it for the top-down car scenario.

Thanks
hey guys.

I'm sorry, I kniw this is an old post, but I'm having issues with killOrthogonalVelocity.

The car just doesn't work. I turn a little bit and accelerate and it turns 360 like the movies. :S (car chase)

Anyone knows a working killOrthogonalVelocity() with 2.0.1a?

Thanks
Hi,

Can someone explain to me what this line of code is doing? I am not sure what multiplying a vector by the dot product is actually doing?

sidewaysAxis.Multiply(b2Math.b2Dot(velocity,sidewaysAxis))


Regards

i
makc wrote:
CyberPunK wrote:...i noticed the problems thack mack also noticed. The car seems to go faster at some angle and sometimes it steers faster then normal. I guess it has something to do with the killOrthogonalVelocity function, but i wasn't able to find out a solution.
It was caused by this bug.


makc wrote:clark, android's code works very well with latest svn fixes. although it claims to "kill orthogonal velocity", natural skidding occurs due to joints; but if you want additional "tensor" damping, simply modify killOrthogonalVelocity() to add small amount of targetBody.GetXForm().R.col1 in.


Can someone post the Box2d classes with the latest svn fixes ?
Actually, instead of learning more about box2d i spend all my time trying to get a working version of Box2d...
I think i am not alone in this situation.
Thank you in advance.
No idea what i'm doing yet but managed to convert it to work with box2dAS

I use flash develop, so its a case of dropping the box2DAS folder in the src folder and then right click the box2d.swc file and choose add to Library.
Put this code in src folder and run.

No idea if its right or wrong but 'seems' to work.
Still learning 🙁

If anybody has better ways, or an example of how your apply the tensor stuff would love to see 🤓

Code: Select all

package
{

   import Box2DAS.Collision.*;// bounding box of our world
   import Box2DAS.Common.V2;
   import flash.events.Event;
   import flash.events.KeyboardEvent;
   import flash.ui.Keyboard;

   import Box2DAS.Common.*;// for vector(define gravity)
   import Box2DAS.Dynamics.*;// define bodies and define world
   import Box2DAS.Dynamics.Joints.*;
   import Box2DAS.Collision.Shapes.*;// define our shapes
   import flash.display.*;// sprite class
   
   public class CarTest2 extends Sprite
   {
      private const MAX_STEER_ANGLE:Number = Math.PI/3;
      private const STEER_SPEED:Number = 1.5;
      private const SIDEWAYS_FRICTION_FORCE:Number = 10;
      private const HORSEPOWERS:Number = 40
      private const CAR_STARTING_POS:V2 = new V2(10,10);

      private const leftRearWheelPosition:V2 = new V2(-1.5,1.90);
      private const rightRearWheelPosition:V2 = new V2(1.5,1.9);
      private const leftFrontWheelPosition:V2 = new V2(-1.5,-1.9);
      private const rightFrontWheelPosition:V2 = new V2(1.5,-1.9);

      private var engineSpeed:Number =0;
      private var steeringAngle:Number = 0

      private var myWorld:b2World;
      private var rightWheel:b2Body;
      private var leftWheel:b2Body;
      private var leftJoint:b2RevoluteJoint;
      private var rightJoint:b2RevoluteJoint;
      private var rightRearWheel:b2Body;
      private var leftRearWheel:b2Body;
      private var body:b2Body;
      private var cone:b2Body;
      private var debug:b2DebugDraw;
      
      public function CarTest2():void
      {
         if (stage) init();
         else addEventListener(Event.ADDED_TO_STAGE, init);
      }
      
      private function init(e:Event = null):void
      {
         removeEventListener(Event.ADDED_TO_STAGE, init);
         stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed_handler);
         stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased_handler);
         addEventListener(Event.ENTER_FRAME, Update);
         
         
         var gravity:V2 = new V2(0.0);
         var doSleep:Boolean = true;
         myWorld = new b2World(gravity, doSleep);
      
         //Create some static stuff
         var staticDef:b2BodyDef = new b2BodyDef();
         staticDef.type = b2Body.b2_staticBody;
         staticDef.position.v2 = new V2(5, 20);
         
         var staticBox:b2PolygonShape  = new b2PolygonShape();
         staticBox.SetAsBox(5, 5);
         
         var staticBoxFixtureDef:b2FixtureDef = new b2FixtureDef();
         staticBoxFixtureDef.shape = staticBox;
         
         var staticBoxBody:b2Body  = myWorld.CreateBody(staticDef)
         staticBoxBody.CreateFixture(staticBoxFixtureDef);
         staticDef.position.x = 25;
         
         
         
         var staticBoxBody2:b2Body = myWorld.CreateBody(staticDef);
         staticBoxBody2.CreateFixture(staticBoxFixtureDef);
         staticDef.position.v2 = new V2(15, 24);


         // define our body
         var bodyDef:b2BodyDef = new b2BodyDef();
         bodyDef.type = b2Body.b2_dynamicBody;
         bodyDef.linearDamping = 1;
         bodyDef.angularDamping = 1;
         bodyDef.position.v2 = CAR_STARTING_POS.clone();

         body = myWorld.CreateBody(bodyDef);
         //body.set.SetMassFromShapes();
         
         //define cone
         var coneDef:b2BodyDef = new b2BodyDef();
         coneDef.type = b2Body.b2_dynamicBody;
         coneDef.linearDamping = 1;
         coneDef.angularDamping = 1;
         coneDef.position.v2 = new V2(13,10)

         cone = myWorld.CreateBody(coneDef);
         
         

         var leftWheelDef:b2BodyDef = new b2BodyDef();
         leftWheelDef.type = b2Body.b2_dynamicBody;
         leftWheelDef.position.v2 = CAR_STARTING_POS.clone();
         trace(leftWheelDef.position.v2);
         leftWheelDef.position.v2 = leftWheelDef.position.v2.add(leftFrontWheelPosition);
         trace(leftWheelDef.position.v2);
         leftWheel = myWorld.CreateBody(leftWheelDef);

         var rightWheelDef:b2BodyDef = new b2BodyDef();
         rightWheelDef.type = b2Body.b2_dynamicBody;
         rightWheelDef.position.v2 = CAR_STARTING_POS.clone();
         rightWheelDef.position.v2 = rightWheelDef.position.v2.add(rightFrontWheelPosition);
         rightWheel = myWorld.CreateBody(rightWheelDef);

         var leftRearWheelDef:b2BodyDef = new b2BodyDef();
         leftRearWheelDef.type = b2Body.b2_dynamicBody;
         leftRearWheelDef.position.v2 = CAR_STARTING_POS.clone();
         leftRearWheelDef.position.v2 = leftRearWheelDef.position.v2.add(leftRearWheelPosition);
         leftRearWheel = myWorld.CreateBody(leftRearWheelDef);

         var rightRearWheelDef:b2BodyDef = new b2BodyDef();
         rightRearWheelDef.type = b2Body.b2_dynamicBody;
         rightRearWheelDef.position.v2 = CAR_STARTING_POS.clone();
         rightRearWheelDef.position.v2 = rightRearWheelDef.position.v2.add(rightRearWheelPosition);
         rightRearWheel = myWorld.CreateBody(rightRearWheelDef);

         // define our shapes
         var boxDef:b2PolygonShape = new b2PolygonShape();
         boxDef.SetAsBox(1.5,2.5);
         //boxDef.density = 1;
         body.CreateFixtureShape(boxDef, 1);
         
         //cone shape
         var conesDef:b2PolygonShape = new b2PolygonShape();
         conesDef.SetAsBox(0.2,0.2);
         cone.CreateFixtureShape(conesDef,1);

         //Left Wheel shape
         var leftWheelShapeDef:b2PolygonShape = new b2PolygonShape();
         leftWheelShapeDef.SetAsBox(0.2,0.5);
         //leftWheelShapeDef.density = 1;
         leftWheel.CreateFixtureShape(leftWheelShapeDef,1);

         //Right Wheel shape
         var rightWheelShapeDef:b2PolygonShape = new b2PolygonShape();
         rightWheelShapeDef.SetAsBox(0.2,0.5);
         //rightWheelShapeDef.density = 1;
         rightWheel.CreateFixtureShape(rightWheelShapeDef,1);

         //Left Wheel shape
         var leftRearWheelShapeDef:b2PolygonShape = new b2PolygonShape();
         leftRearWheelShapeDef.SetAsBox(0.2,0.5);
         //leftRearWheelShapeDef.density = 1;
         leftRearWheel.CreateFixtureShape(leftRearWheelShapeDef,1);

         //Right Wheel shape
         var rightRearWheelShapeDef:b2PolygonShape = new b2PolygonShape();
         rightRearWheelShapeDef.SetAsBox(0.2,0.5);
         //rightRearWheelShapeDef.density = 1;
         rightRearWheel.CreateFixtureShape(rightRearWheelShapeDef,1);
   /*
         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:b2RevoluteJointDef = new b2RevoluteJointDef();
         rightJointDef.Initialize(body, rightWheel, rightWheel.GetWorldCenter());
         rightJointDef.enableMotor = true;
         rightJointDef.maxMotorTorque = 100;

         leftJoint = b2RevoluteJoint(myWorld.CreateJoint(leftJointDef));
         rightJoint = b2RevoluteJoint(myWorld.CreateJoint(rightJointDef));

         var leftRearJointDef:b2PrismaticJointDef = new b2PrismaticJointDef();
         leftRearJointDef.Initialize(body, leftRearWheel, leftRearWheel.GetWorldCenter(), new V2(1,0));
         leftRearJointDef.enableLimit = true;
         leftRearJointDef.lowerTranslation = leftRearJointDef.upperTranslation = 0;

         var rightRearJointDef:b2PrismaticJointDef = new b2PrismaticJointDef();
         rightRearJointDef.Initialize(body, rightRearWheel, rightRearWheel.GetWorldCenter(), new V2(1,0));
         rightRearJointDef.enableLimit = true;
         rightRearJointDef.lowerTranslation = rightRearJointDef.upperTranslation = 0;

         myWorld.CreateJoint(leftRearJointDef);
         myWorld.CreateJoint(rightRearJointDef);


         //Debugdraw
          debug = new b2DebugDraw();
          stage.addChild(debug);

      }

      //========== FUNCTIONS ==========

      //This function applies a "friction" in a direction orthogonal to the body's axis.
      private function killOrthogonalVelocity(targetBody:b2Body):void
      {
         /**/
         var localPoint:V2 = new V2(0,0);
         var velocity:V2 = targetBody.GetLinearVelocityFromLocalPoint(localPoint);
         
         var sidewaysAxis:V2 = targetBody.GetTransform().r.c2.clone();
         //sidewaysAxis.Multiply(b2Math.b2Dot(velocity,sidewaysAxis))
         sidewaysAxis.multiplyN(velocity.dot(sidewaysAxis));
         targetBody.SetLinearVelocity(sidewaysAxis);//targetBody.GetWorldPoint(localPoint));
      }
      
      private function keyPressed_handler(e:KeyboardEvent):void
      {
         if(e.keyCode == Keyboard.UP){
            body.SetAwake(true)
            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
         }
      }

      private function keyReleased_handler(e:KeyboardEvent):void
      {
         if(e.keyCode == Keyboard.UP || e.keyCode == Keyboard.DOWN){
            engineSpeed = 0;
         }
         if(e.keyCode == Keyboard.LEFT || e.keyCode == Keyboard.RIGHT){
            steeringAngle = 0;
         }
      }
      
      private   function Update(e:Event):void {
         
         debug.world = myWorld;
         debug.scale = 30;
         debug.alpha = 0.2;
         debug.Draw();
            
         var timeStep:Number = 1.0 / 30.0;
         myWorld.Step ( timeStep, 10, 20 );   
         
         
         
         killOrthogonalVelocity(leftWheel);
         killOrthogonalVelocity(rightWheel);
         killOrthogonalVelocity(leftRearWheel);
         killOrthogonalVelocity(rightRearWheel);

         //Driving
         var ldirection:V2 = leftWheel.GetTransform().r.c2.clone()
         ldirection.multiplyN(engineSpeed);
         var rdirection:V2 = rightWheel.GetTransform().r.c2.clone()
         rdirection.multiplyN(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);
         
      }
   }
}
Hello,
I have tried to update the code to Box2D version 2.1,
looks like everything is allright, except for one little detail:
the car does not move at all,
would anyone please try my code and see the stupid "detail" I forgot?

Thanks and sorry for not being smarter,
Philippe

Code: Select all

package {

   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
   import flash.events.KeyboardEvent; 
   import flash.events.Event; 
   
   public class CarTest extends Sprite {
      public const MAX_STEER_ANGLE:Number = Math.PI/3;
      public const STEER_SPEED:Number = 1.5;
      public const SIDEWAYS_FRICTION_FORCE:Number = 10;
      public const HORSEPOWERS:Number = 40;
      public const CAR_STARTING_POS:b2Vec2 = new b2Vec2(10,10);
      
      public const leftRearWheelPosition:b2Vec2 = new b2Vec2(-1.5,1.90);
      public const rightRearWheelPosition:b2Vec2 = new b2Vec2(1.5,1.9);
      public const leftFrontWheelPosition:b2Vec2 = new b2Vec2(-1.5,-1.9);
      public const rightFrontWheelPosition:b2Vec2 = new b2Vec2(1.5,-1.9);
      
      public var engineSpeed:Number =0;
      public var steeringAngle:Number = 0
      
      public var myWorld:b2World;
      
      public var fixtureDef:b2FixtureDef = new b2FixtureDef();
      
      public var carBody:b2Body;
      public var leftWheel:b2Body;
      public var rightWheel:b2Body;
      public var leftRearWheel:b2Body;
      public var rightRearWheel:b2Body;
      public var leftJoint:b2RevoluteJoint;
      public var rightJoint:b2RevoluteJoint;
      
      public function CarTest():void {
         myWorld=new b2World(new b2Vec2(0,0.0),true);
         
         var boxDef:b2PolygonShape = new b2PolygonShape();
         
         //Create some static stuff
         var staticDef:b2BodyDef = new b2BodyDef();
         staticDef.position.Set(5,20);
         var staticBox:b2PolygonShape = new b2PolygonShape();
         boxDef.SetAsBox(5, 5);
         fixtureDef.shape = boxDef;
         var body:b2Body = myWorld.CreateBody(staticDef);
         body.CreateFixture(fixtureDef);
         staticDef.position.x = 25;
         body = myWorld.CreateBody(staticDef);
         body.CreateFixture(fixtureDef);
         staticDef.position.Set(15, 24);
         body = myWorld.CreateBody(staticDef);
         body.CreateFixture(fixtureDef);
         
         
         // define our body
         var bodyDef:b2BodyDef = new b2BodyDef();
         boxDef.SetAsBox(1.5,2.5);
         bodyDef.linearDamping = 1;
         bodyDef.angularDamping = 1;
         bodyDef.position = CAR_STARTING_POS.Copy();
         
         // this is new!!
         fixtureDef.shape = boxDef;
         fixtureDef.friction=1;// was boxDef.friction=1;
         fixtureDef.density=1;// was boxDef.density=0;
         carBody = myWorld.CreateBody(bodyDef);
         carBody.CreateFixture(fixtureDef);// was body.CreateShape(boxDef);
         
         var leftWheelDef:b2BodyDef = new b2BodyDef();
         leftWheelDef.position = CAR_STARTING_POS.Copy();
         leftWheelDef.position.Add(leftFrontWheelPosition);
         // this is new!!
         boxDef.SetAsBox(0.2,0.5);
         fixtureDef.shape = boxDef;
         fixtureDef.friction=1;// was boxDef.friction=1;
         fixtureDef.density=1;// was boxDef.density=0;
         leftWheel = myWorld.CreateBody(leftWheelDef);
         leftWheel.CreateFixture(fixtureDef);
         
         var rightWheelDef:b2BodyDef = new b2BodyDef();
         rightWheelDef.position = CAR_STARTING_POS.Copy();
         rightWheelDef.position.Add(rightFrontWheelPosition);
         // this is new!!
         boxDef.SetAsBox(0.2,0.5);
         fixtureDef.shape = boxDef;
         fixtureDef.friction=1;// was boxDef.friction=1;
         fixtureDef.density=1;// was boxDef.density=0;
         rightWheel = myWorld.CreateBody(rightWheelDef);
         rightWheel.CreateFixture(fixtureDef);
         
         var leftRearWheelDef:b2BodyDef = new b2BodyDef();
         leftRearWheelDef.position = CAR_STARTING_POS.Copy();
         leftRearWheelDef.position.Add(leftRearWheelPosition);
         // this is new!!
         boxDef.SetAsBox(0.2,0.5);
         fixtureDef.shape = boxDef;
         fixtureDef.friction=1;// was boxDef.friction=1;
         fixtureDef.density=1;// was boxDef.density=0;
         leftRearWheel = myWorld.CreateBody(leftRearWheelDef);
         leftRearWheel.CreateFixture(fixtureDef);
         
         var rightRearWheelDef:b2BodyDef = new b2BodyDef();
         rightRearWheelDef.position = CAR_STARTING_POS.Copy();
         rightRearWheelDef.position.Add(rightRearWheelPosition);
         // this is new!!
         boxDef.SetAsBox(0.2,0.5);
         fixtureDef.shape = boxDef;
         fixtureDef.friction=1;// was boxDef.friction=1;
         fixtureDef.density=1;// was boxDef.density=0;
         rightRearWheel = myWorld.CreateBody(rightRearWheelDef);
         rightRearWheel.CreateFixture(fixtureDef);
         
         var leftJointDef:b2RevoluteJointDef = new b2RevoluteJointDef();
         leftJointDef.Initialize(carBody, leftWheel, leftWheel.GetWorldCenter());
         leftJointDef.enableMotor = true;
         leftJointDef.maxMotorTorque = 100;
         
         var rightJointDef:b2RevoluteJointDef = new b2RevoluteJointDef();
         rightJointDef.Initialize(carBody, rightWheel, rightWheel.GetWorldCenter());
         rightJointDef.enableMotor = true;
         rightJointDef.maxMotorTorque = 100;
         
         leftJoint = b2RevoluteJoint(myWorld.CreateJoint(leftJointDef));
         rightJoint = b2RevoluteJoint(myWorld.CreateJoint(rightJointDef));
         
         var leftRearJointDef:b2PrismaticJointDef = new b2PrismaticJointDef();
         leftRearJointDef.Initialize(carBody, leftRearWheel, leftRearWheel.GetWorldCenter(), new b2Vec2(1,0));
         leftRearJointDef.enableLimit = true;
         leftRearJointDef.lowerTranslation = leftRearJointDef.upperTranslation = 0;
         
         var rightRearJointDef:b2PrismaticJointDef = new b2PrismaticJointDef();
         rightRearJointDef.Initialize(carBody, rightRearWheel, rightRearWheel.GetWorldCenter(), new b2Vec2(1,0));
         rightRearJointDef.enableLimit = true;
         rightRearJointDef.lowerTranslation = rightRearJointDef.upperTranslation = 0;
         
         myWorld.CreateJoint(leftRearJointDef);
         myWorld.CreateJoint(rightRearJointDef);
         
         
         // debug draw
         debug_draw();
         stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed_handler);
         stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased_handler);
         stage.addEventListener(Event.ENTER_FRAME, Update, false, 0 , true);
      }
      public function debug_draw():void {
         var m_sprite:Sprite;
         m_sprite = new Sprite();
         addChild(m_sprite);
         var dbgDraw:b2DebugDraw = new b2DebugDraw();
         var dbgSprite:Sprite = new Sprite();
         m_sprite.addChild(dbgSprite);
         dbgDraw.SetSprite(m_sprite); // was dbgDraw.m_sprite=m_sprite;
         dbgDraw.SetDrawScale(20); // was dbgDraw.m_drawScale=30;
         //dbgDraw.SetAlpha(1); // was dbgDraw.m_alpha=1;
         dbgDraw.SetFillAlpha(0.5); // was dbgDraw.m_fillAlpha=0.5;
         dbgDraw.SetLineThickness(1); // was dbgDraw.m_lineThickness=1;
         dbgDraw.SetFlags(b2DebugDraw.e_shapeBit); // was dbgDraw.m_drawFlags=b2DebugDraw.e_shapeBit;
         myWorld.SetDebugDraw(dbgDraw);
      }
      //========== FUNCTIONS ==========
      
      //This function applies a "friction" in a direction orthogonal to the body's axis.
      public function killOrthogonalVelocity(targetBody:b2Body):void {
         var localPoint:b2Vec2 = new b2Vec2(0,0);
         var velocity:b2Vec2 = targetBody.GetLinearVelocityFromLocalPoint(localPoint);
         var sidewaysAxis:b2Vec2 = targetBody.GetTransform().R.col2.Copy();
         //var sidewaysAxis = targetBody.GetXForm().R.col2.Copy();
         //sidewaysAxis.Multiply(b2Math.b2Dot(velocity,sidewaysAxis))
         sidewaysAxis.Multiply(b2Math.Dot(velocity, sidewaysAxis));
         targetBody.SetLinearVelocity(sidewaysAxis);//targetBody.GetWorldPoint(localPoint));
      }
      
      
      public function keyPressed_handler(e:KeyboardEvent):void {
         trace (e.keyCode);
         trace (carBody.IsAwake());
         if(e.keyCode == 38){ //UP
            //carBody.SetAwake(false);
            engineSpeed = -HORSEPOWERS;
         }
         if(e.keyCode == 40){ //DOWN
            engineSpeed = HORSEPOWERS;
         }
         if(e.keyCode == 39){ //RIGHT
            steeringAngle = MAX_STEER_ANGLE;
         }
         if(e.keyCode == 37){  //LEFT
            steeringAngle = -MAX_STEER_ANGLE;
         }
      }
      
      public function keyReleased_handler(e:KeyboardEvent):void {
         if(e.keyCode == 38 || e.keyCode == 40){
            engineSpeed = 0;
         }
         if(e.keyCode == 37 || e.keyCode == 39){
            steeringAngle = 0;
         }
      }
      

      
      public function Update(e:Event):void {
         myWorld.Step(1 / 30, 8, 8);
         // this is new!
         //myWorld.ClearForces();
         // this is new!!
         myWorld.DrawDebugData();
         
         killOrthogonalVelocity(leftWheel);
         killOrthogonalVelocity(rightWheel);
         killOrthogonalVelocity(leftRearWheel);
         killOrthogonalVelocity(rightRearWheel);
      
         //Driving
         var ldirection:b2Vec2 = leftWheel.GetTransform().R.col2.Copy();
         ldirection.Multiply(engineSpeed);
         var rdirection:b2Vec2 = rightWheel.GetTransform().R.col2.Copy();
         rdirection.Multiply(engineSpeed);
         trace ("****************", ldirection.y, rdirection.y);
         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);
         
         
      }
   }
}
In fact, it was easy,
I just had forgotten to set all bodydefs of the car to type dynamic,
here is the solution:

Code: Select all

package {

   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
   import flash.events.KeyboardEvent; 
   import flash.events.Event; 
   
   public class CarTest extends Sprite {
      public const MAX_STEER_ANGLE:Number = Math.PI/3;
      public const STEER_SPEED:Number = 1.5;
      public const SIDEWAYS_FRICTION_FORCE:Number = 10;
      public const HORSEPOWERS:Number = 40;
      public const CAR_STARTING_POS:b2Vec2 = new b2Vec2(10,10);
      
      public const leftRearWheelPosition:b2Vec2 = new b2Vec2(-1.5,1.90);
      public const rightRearWheelPosition:b2Vec2 = new b2Vec2(1.5,1.9);
      public const leftFrontWheelPosition:b2Vec2 = new b2Vec2(-1.5,-1.9);
      public const rightFrontWheelPosition:b2Vec2 = new b2Vec2(1.5,-1.9);
      
      public var engineSpeed:Number =0;
      public var steeringAngle:Number = 0
      
      public var myWorld:b2World;
      
      public var fixtureDef:b2FixtureDef = new b2FixtureDef();
      
      public var carBody:b2Body;
      public var leftWheel:b2Body;
      public var rightWheel:b2Body;
      public var leftRearWheel:b2Body;
      public var rightRearWheel:b2Body;
      public var leftJoint:b2RevoluteJoint;
      public var rightJoint:b2RevoluteJoint;
      
      public function CarTest():void {
         myWorld=new b2World(new b2Vec2(0,0.0),true);
         
         var boxDef:b2PolygonShape = new b2PolygonShape();
         
         //Create some static stuff
         var staticDef:b2BodyDef = new b2BodyDef();
         staticDef.position.Set(5,20);
         var staticBox:b2PolygonShape = new b2PolygonShape();
         boxDef.SetAsBox(5, 5);
         fixtureDef.shape = boxDef;
         var body:b2Body = myWorld.CreateBody(staticDef);
         body.CreateFixture(fixtureDef);
         staticDef.position.x = 25;
         body = myWorld.CreateBody(staticDef);
         body.CreateFixture(fixtureDef);
         staticDef.position.Set(15, 24);
         body = myWorld.CreateBody(staticDef);
         body.CreateFixture(fixtureDef);
         
         // define our body
         var bodyDef:b2BodyDef = new b2BodyDef();
         boxDef.SetAsBox(1.5,2.5);
         bodyDef.linearDamping = 1;
         bodyDef.angularDamping = 1;
         bodyDef.position = CAR_STARTING_POS.Copy();
         bodyDef.type=b2Body.b2_dynamicBody;

         fixtureDef.shape = boxDef;
         fixtureDef.friction=1;
         fixtureDef.density=1;
         carBody = myWorld.CreateBody(bodyDef);
         carBody.CreateFixture(fixtureDef);
         
         var leftWheelDef:b2BodyDef = new b2BodyDef();
         leftWheelDef.type=b2Body.b2_dynamicBody;
         leftWheelDef.position = CAR_STARTING_POS.Copy();
         leftWheelDef.position.Add(leftFrontWheelPosition);
         
         boxDef.SetAsBox(0.2,0.5);
         fixtureDef.shape = boxDef;
         fixtureDef.friction=1;
         fixtureDef.density=1;
         leftWheel = myWorld.CreateBody(leftWheelDef);
         leftWheel.CreateFixture(fixtureDef);
         
         var rightWheelDef:b2BodyDef = new b2BodyDef();
         rightWheelDef.type=b2Body.b2_dynamicBody;
         rightWheelDef.position = CAR_STARTING_POS.Copy();
         rightWheelDef.position.Add(rightFrontWheelPosition);
         
         boxDef.SetAsBox(0.2,0.5);
         fixtureDef.shape = boxDef;
         fixtureDef.friction=1;
         fixtureDef.density=1;
         rightWheel = myWorld.CreateBody(rightWheelDef);
         rightWheel.CreateFixture(fixtureDef);
         
         var leftRearWheelDef:b2BodyDef = new b2BodyDef();
         leftRearWheelDef.type=b2Body.b2_dynamicBody;
         leftRearWheelDef.position = CAR_STARTING_POS.Copy();
         leftRearWheelDef.position.Add(leftRearWheelPosition);
         
         boxDef.SetAsBox(0.2,0.5);
         fixtureDef.shape = boxDef;
         fixtureDef.friction=1;
         fixtureDef.density=1;
         leftRearWheel = myWorld.CreateBody(leftRearWheelDef);
         leftRearWheel.CreateFixture(fixtureDef);
         
         var rightRearWheelDef:b2BodyDef = new b2BodyDef();
         rightRearWheelDef.type=b2Body.b2_dynamicBody;
         rightRearWheelDef.position = CAR_STARTING_POS.Copy();
         rightRearWheelDef.position.Add(rightRearWheelPosition);

         boxDef.SetAsBox(0.2,0.5);
         fixtureDef.shape = boxDef;
         fixtureDef.friction=1;
         fixtureDef.density=1;
         rightRearWheel = myWorld.CreateBody(rightRearWheelDef);
         rightRearWheel.CreateFixture(fixtureDef);
         
         var leftJointDef:b2RevoluteJointDef = new b2RevoluteJointDef();
         leftJointDef.Initialize(carBody, leftWheel, leftWheel.GetWorldCenter());
         leftJointDef.enableMotor = true;
         leftJointDef.maxMotorTorque = 100;
         
         var rightJointDef:b2RevoluteJointDef = new b2RevoluteJointDef();
         rightJointDef.Initialize(carBody, rightWheel, rightWheel.GetWorldCenter());
         rightJointDef.enableMotor = true;
         rightJointDef.maxMotorTorque = 100;
         
         leftJoint = b2RevoluteJoint(myWorld.CreateJoint(leftJointDef));
         rightJoint = b2RevoluteJoint(myWorld.CreateJoint(rightJointDef));
         
         var leftRearJointDef:b2PrismaticJointDef = new b2PrismaticJointDef();
         leftRearJointDef.Initialize(carBody, leftRearWheel, leftRearWheel.GetWorldCenter(), new b2Vec2(1,0));
         leftRearJointDef.enableLimit = true;
         leftRearJointDef.lowerTranslation = leftRearJointDef.upperTranslation = 0;
         
         var rightRearJointDef:b2PrismaticJointDef = new b2PrismaticJointDef();
         rightRearJointDef.Initialize(carBody, rightRearWheel, rightRearWheel.GetWorldCenter(), new b2Vec2(1,0));
         rightRearJointDef.enableLimit = true;
         rightRearJointDef.lowerTranslation = rightRearJointDef.upperTranslation = 0;
         
         myWorld.CreateJoint(leftRearJointDef);
         myWorld.CreateJoint(rightRearJointDef);
         
         
         // debug draw
         debug_draw();
         stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed_handler);
         stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased_handler);
         stage.addEventListener(Event.ENTER_FRAME, Update, false, 0 , true);
      }
      public function debug_draw():void {
         var m_sprite:Sprite;
         m_sprite = new Sprite();
         addChild(m_sprite);
         var dbgDraw:b2DebugDraw = new b2DebugDraw();
         var dbgSprite:Sprite = new Sprite();
         m_sprite.addChild(dbgSprite);
         dbgDraw.SetSprite(m_sprite);
         dbgDraw.SetDrawScale(20);
         //dbgDraw.SetAlpha(1);
         dbgDraw.SetFillAlpha(0.5);
         dbgDraw.SetLineThickness(1);
         dbgDraw.SetFlags(b2DebugDraw.e_shapeBit);
         myWorld.SetDebugDraw(dbgDraw);
      }
      
      //This function applies a "friction" in a direction orthogonal to the body's axis.
      public function killOrthogonalVelocity(targetBody:b2Body):void {
         var localPoint:b2Vec2 = new b2Vec2(0,0);
         var velocity:b2Vec2 = targetBody.GetLinearVelocityFromLocalPoint(localPoint);
         var sidewaysAxis:b2Vec2 = targetBody.GetTransform().R.col2.Copy();
         sidewaysAxis.Multiply(b2Math.Dot(velocity, sidewaysAxis));
         targetBody.SetLinearVelocity(sidewaysAxis);//targetBody.GetWorldPoint(localPoint));
      }
      
      
      public function keyPressed_handler(e:KeyboardEvent):void {
         trace (e.keyCode);
         trace (carBody.IsAwake());
         if(e.keyCode == 38){ //UP
            engineSpeed = -HORSEPOWERS;
         }
         if(e.keyCode == 40){ //DOWN
            engineSpeed = HORSEPOWERS;
         }
         if(e.keyCode == 39){ //RIGHT
            steeringAngle = MAX_STEER_ANGLE;
         }
         if(e.keyCode == 37){  //LEFT
            steeringAngle = -MAX_STEER_ANGLE;
         }
      }
      
      public function keyReleased_handler(e:KeyboardEvent):void {
         if(e.keyCode == 38 || e.keyCode == 40){
            engineSpeed = 0;
         }
         if(e.keyCode == 37 || e.keyCode == 39){
            steeringAngle = 0;
         }
      }
      

      
      public function Update(e:Event):void {
         myWorld.Step(1 / 30, 8, 8);
         // this is new!
         myWorld.ClearForces();
         // this is new!!
         myWorld.DrawDebugData();
         
         killOrthogonalVelocity(leftWheel);
         killOrthogonalVelocity(rightWheel);
         killOrthogonalVelocity(leftRearWheel);
         killOrthogonalVelocity(rightRearWheel);
      
         //Driving
         var ldirection:b2Vec2 = leftWheel.GetTransform().R.col2.Copy();
         ldirection.Multiply(engineSpeed);
         var rdirection:b2Vec2 = rightWheel.GetTransform().R.col2.Copy();
         rdirection.Multiply(engineSpeed);
         leftWheel.ApplyForce(ldirection, leftWheel.GetPosition());
         rightWheel.ApplyForce(rdirection, rightWheel.GetPosition());
      
         //Steering
         var mspeed:Number;
         
         mspeed = steeringAngle - leftJoint.GetJointAngle();
         trace (mspeed);
         leftJoint.SetMotorSpeed(mspeed * STEER_SPEED);
         mspeed = steeringAngle - rightJoint.GetJointAngle();
         rightJoint.SetMotorSpeed(mspeed * STEER_SPEED);
         
         
      }
   }
}
Check out my library for some decent, realistic top-down car physics (3rd demo in):

http://quickb2.dougkoellmer.com/bin/qb2DemoReel.swf

The source code can be found here:

http://code.google.com/p/quickb2/

If you're patient enough you can just extract the source code and adapt it to work with Box2D directly. I'd appreciate feedback on QuickB2 though of course 🙂

(the following is taken from another post I made...)

Cars are defined by the following properties:
gear ratios and number of gears.
torque curves (engine performance graphs that determine torque output at a particular RPM).
differentials
center of mass in the z direction (x/y center of mass is implied from the car body's geometry).
arbitrary tire placement and number of tires.
tire friction, including rolling friction.
tire mass, width, and radius.
whether a given tire turns and/or brakes and/or is driven
turn angle.
shift timings.
manual or automatic transmissions.
transmission efficiency.
traction control (sets whether or not you can do burn-outs and such).

It takes into account most things you'd expect from a car simulation, like weight transfer, tire spin, handbrake turns, etc. The braking and friction model isn't insanely realistic, but close enough for most purposes. You should be able to put in real-life car properties and get a reasonable facsimile. AI is modular and hot-swappable. You give a car a brain, and that brain sets "data ports" on the car that determine percentage of throttle, turn and brake each time step. The brain in turn is controlled either by player input, or by AI routines (path-finding, path-following, etc.).
wonderful demos!

your soft bodies seem a lot more stable than most.
i love that your slice demo remembers partial slices.
and your car AI is very clever looking.
all of your joints seem very elegant compared to the default box2d ones.

Car sliding i was not content with. Possibly just too real for what i feel a game would want.
when you start to slide you are a little too out of control. my favorite sliding mechanic is in an old game called Recoil. through a careful succession of hard turning and switching between forward and reverse i could stay moving in the direction of the power-slide while aiming my tank in other directions to fire at my foes.
what you have is pretty close to Mario-Cart though probably.
another possible mechanic to add would be like the N64 StarWars Racing game. their "power slide" was to lose all traction, turn to the desired direction, wait to barely pass the corner and release, regaining full traction/momentum in the new direction.

1 big question for me.
your distance joint doesn't seem stretch like the box2d one. is there a parameter i can modify to make box2d distance joints very strict like that?

I'm a WCK user.
hmm your slice demo can break a bit.
adding many small slices, then cutting one big slide through the middle, it can turn dark grey. then the future slices seem to come out of nowhere as the dark-grey shape stays the same.

also I'm surprised you don't reset worlds when going next and previous like other test-beds i see.

Original thread: https://box2d.org/forum/viewtopic.php?t=1547