9/08/2011

How To Create A Monster Truck Game With Cocos2d and Box2d

I read "Two ways to make Box2D cars" several days ago. Since I'm learning cocos2d and box2d, so I decide to translate it from actionscript into objective-C. I'm a freshman, please let me know if there are any errors.

Let's start. Firstly, create a new cocos2d project by selecting cocos2d Application-Mac template and name the project "MonsterTruck".

Then next, we need add Box2d to the project because the template doesn't contain Box2D module. You can follow this toturial if you don't know how to do it. Two files (GLES-Render.h and GL-ES-Render.mm) mentioned but not given in the tutorial are located in "cocos2d-iphone-1.0.1/tests/Box2DTestBed-Cocos2dIntegration". Drag them over to the class folder in Xcode, and make sure "Copy items into destination group's folder (if needed)" is checked.

Right click on Classes, choose "Add\New File...", choose "cocos2d templates\CCNode class", make sure Subclass of CCNode is selected, and click next. Name the file MonsterTruck.mm and make sure "Also create MonsterTruck.h" is checked. Then replace MonsterTruck.h with the following:
#import "cocos2d.h"
#import "Box2D.h"
#import "cocos2d.h"

#define PTM_RATIO 32.0f

@interface MonsterTruck : CCNode
{
@private
  b2World *_world;
  b2Body *truckBody, *frontWheel, *rearWheel, *frontAxle, *rearAxle;
  b2PrismaticJoint *frontSpring, *rearSpring;
  b2RevoluteJoint *frontMotor, *rearMotor;
}

- (void)createTruckWithWorld:(b2World *)world withPosition:(CGPoint)pos;
- (CGPoint)position;
- (void)updateSprings;
- (void)upArrowPressed;
- (void)downArrowPressed;
- (void)upDownArrowReleased;
- (void)leftArrowPressed;
- (void)rightArrowPressed;
- (void)leftRightArrowReleased;
- (void)destroy;

@end
Now we can create a monster truck step by step. Remember to convert pixels/meters to meters/pixels. The values of the parameters may not be correct, I just wanna make a running truck.
#import "MonsterTruck.h"

@implementation MonsterTruck

// get the position of the truck.
- (CGPoint)position
{
  return ccp(truckBody->GetPosition().x*PTM_RATIO, truckBody->GetPosition().y*PTM_RATIO);
}

- (void)addTruckWithCoords:(CGPoint)pos
{  
  // Crate the body of the Truck.
  // use two box to make it looks like a truck.
  {
    b2BodyDef bd;
    bd.type = b2_dynamicBody;
    bd.position.Set(pos.x/PTM_RATIO, pos.y/PTM_RATIO);
    bd.angularDamping = 0.2;
    bd.linearDamping = 0.2;
    
    truckBody = _world->CreateBody(&bd);
    bd.linearDamping = 0.2;
    
    b2PolygonShape shape;
    
    // the main body
    shape.SetAsBox(62.0/PTM_RATIO, 15.0/PTM_RATIO, b2Vec2(0.0, 18/PTM_RATIO), 0.0);
    
    b2FixtureDef fd;
    fd.shape = &shape;
    fd.density = 0.1;
    fd.friction = 0.3;
    fd.restitution = 0.1;
    fd.filter.groupIndex = -1;
    truckBody->CreateFixture(&fd);
    
    // a smaller box on the main body
    shape.SetAsBox(30.0/PTM_RATIO, 7.0/PTM_RATIO, b2Vec2(-26.0/PTM_RATIO, 40/PTM_RATIO), 0.0);
    truckBody->CreateFixture(&fd);
    
    // create two frames
    shape.SetAsBox(18.0/PTM_RATIO, 7.0/PTM_RATIO, b2Vec2(39/PTM_RATIO, -8/PTM_RATIO), -M_PI/3);
    truckBody->CreateFixture(&fd);
    shape.SetAsBox(18.0/PTM_RATIO, 7.0/PTM_RATIO, b2Vec2(-39/PTM_RATIO, -8/PTM_RATIO), M_PI/3);
    truckBody->CreateFixture(&fd);
  }
  
  // we need two axle to join the truck body and the wheels together
  // and add two springs to join the truck body and axle together.
  {
    b2PrismaticJointDef pjd;
    pjd.lowerTranslation = -0.3;
    pjd.upperTranslation = 0.5;
    pjd.enableLimit = true;
    pjd.enableMotor = true;
    
    b2BodyDef bd;
    bd.type = b2_dynamicBody;
    bd.allowSleep = false;
    
    b2PolygonShape shape;
    b2FixtureDef fd;
    fd.shape = &shape;
    fd.density = 0.1;
    fd.friction = 0.2;
    fd.restitution = 0.1;
    fd.filter.groupIndex = -1;
    
    // front axle and front spring
    bd.position.Set(pos.x/PTM_RATIO, pos.y/PTM_RATIO);
    
    frontAxle = _world->CreateBody(&bd);
    shape.SetAsBox(18.0/PTM_RATIO, 
                   5.0/PTM_RATIO, 
                   b2Vec2((56-10*cos(M_PI/3))/PTM_RATIO, (-38+10*sin(M_PI/3))/PTM_RATIO), 
                   -M_PI/3);
    frontAxle->CreateFixture(&fd);
    
    pjd.Initialize(truckBody, frontAxle, frontAxle->GetWorldCenter(), 
                   b2Vec2(-cos(M_PI/3), sin(M_PI/3)));
    frontSpring = (b2PrismaticJoint *)_world->CreateJoint(&pjd);
    
    // rear axle and front spring
    bd.position.Set(pos.x/PTM_RATIO, pos.y/PTM_RATIO);
    
    shape.SetAsBox(18.0/PTM_RATIO, 
                   5.0/PTM_RATIO, 
                   b2Vec2((-56+10*cos(M_PI/3))/PTM_RATIO, (-38+10*sin(M_PI/3))/PTM_RATIO), 
                   M_PI/3);
    rearAxle = _world->CreateBody(&bd);
    rearAxle->CreateFixture(&fd);
    
    pjd.Initialize(truckBody, rearAxle, rearAxle->GetWorldCenter(), 
                   b2Vec2(cos(M_PI/3), sin(M_PI/3)));
    rearSpring = (b2PrismaticJoint *)_world->CreateJoint(&pjd);    
  }
  
  // add two big wheels
  {
    float radius = 45.0f;
    b2BodyDef bd;
    bd.type = b2_dynamicBody;
    bd.angularDamping = 0.2;
    bd.linearDamping = 0.2;
    
    b2CircleShape shape;
    shape.m_radius = radius/PTM_RATIO;
    
    b2FixtureDef fd;
    fd.shape = &shape;
    fd.density = 0.2;
    fd.friction = 5;
    fd.restitution = 0.1;
    fd.filter.groupIndex = -1;
    
    // front wheel
    bd.position.Set(frontAxle->GetWorldCenter().x+14*cos(M_PI/3)/PTM_RATIO,
                    frontAxle->GetWorldCenter().y-14*sin(M_PI/3)/PTM_RATIO);
    frontWheel = _world->CreateBody(&bd);
    frontWheel->CreateFixture(&fd);
    
    // front wheel
    bd.position.Set(rearAxle->GetWorldCenter().x-14*cos(M_PI/3)/PTM_RATIO,
                    rearAxle->GetWorldCenter().y-14*sin(M_PI/3)/PTM_RATIO);
    rearWheel = _world->CreateBody(&bd);
    rearWheel->CreateFixture(&fd);
  }
  
  { // add joints
    b2RevoluteJointDef rjd;
    rjd.enableMotor = true;
    
    rjd.Initialize(frontAxle, frontWheel, frontWheel->GetWorldCenter());
    frontMotor = (b2RevoluteJoint*)_world->CreateJoint(&rjd);
    
    rjd.Initialize(rearAxle, rearWheel, rearWheel->GetWorldCenter());
    rearMotor = (b2RevoluteJoint*)_world->CreateJoint(&rjd);
  }
}

- (void)createTruckWithWorld:(b2World *)world withPosition:(CGPoint)pos
{
  _world = world;
  [self addTruckWithCoords:pos];
}

// update springs constantly
- (void)updateSprings
{
  if (frontSpring != NULL && rearSpring != NULL)
  {
    frontSpring->SetMaxMotorForce(20 + abs(100 * pow(frontSpring->GetJointTranslation(), 2)));
    frontSpring->SetMotorSpeed(-10 * pow(frontSpring->GetJointTranslation(), 1));
    
    rearSpring->SetMaxMotorForce(20 + abs(100 * pow(rearSpring->GetJointTranslation(), 2)));
    rearSpring->SetMotorSpeed(-10 * pow(rearSpring->GetJointTranslation(), 1));
  }
}

// methods responsing to key events
- (void)leftArrowPressed
{
  truckBody->ApplyTorque(280.0);
}

- (void)rightArrowPressed
{
  truckBody->ApplyTorque(-280.0);
}

- (void)leftRightArrowReleased
{
  truckBody->ApplyTorque(0.0);
}

- (void)upArrowPressed
{
  frontMotor->SetMotorSpeed(40 * M_PI * -1);
  frontMotor->SetMaxMotorTorque(12);
  rearMotor->SetMotorSpeed(40 * M_PI * -1);
  rearMotor->SetMaxMotorTorque(14);
}

- (void)downArrowPressed
{
  frontMotor->SetMotorSpeed(40 * M_PI * 1);
  frontMotor->SetMaxMotorTorque(14);
  rearMotor->SetMotorSpeed(40 * M_PI * 1);
  rearMotor->SetMaxMotorTorque(12);
}

- (void)upDownArrowReleased
{
  frontMotor->SetMotorSpeed(0);
  frontMotor->SetMaxMotorTorque(0.2);
  rearMotor->SetMaxMotorTorque(0.2);
  rearMotor->SetMotorSpeed(0);
}

- (void) destroy
{
  _world->DestroyJoint(frontMotor);
  _world->DestroyJoint(rearMotor);
  _world->DestroyBody(truckBody);
  _world->DestroyBody(frontWheel);
  _world->DestroyBody(rearWheel);
  _world->DestroyBody(frontAxle);
  _world->DestroyBody(rearAxle);
  
  // since we join truck body and axles with springs,
  // when the truck and axles are destroyed, the springs are never exist.
  // so we needn't destroy the two springs.
  // _world->DestroyJoint(frontSpring);
  // _world->DestroyJoint(rearSpring);
}

- (void)dealloc
{
  [super dealloc];
}

// BTW, if you need update sprite, add the following method and schedule it.
/*
- (void)update
{
  for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
  {
    if (b->GetUserData() != NULL) 
    {
      CCSprite *sprite= (CCSprite*)b->GetUserData();
      sprite.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
      sprite.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
    }
  }
}
*/
@end
Now we can create a truck by importing "MonsterTruck.h" and using method "- (void)createTruckWithWorld:(b2World *)world withPosition:(CGPoint)pos". But there is nothing hold the truck, so we need create terrains to hold it. Create "Terrain.mm" in the same way we create "MonsterTruck.mm". Replace Terrain.h with the following:
#import "Box2D.h"
#import "cocos2d.h"

#define PTM_RATIO 32.0f

@interface Terrain : CCNode 
{
@private
  b2World *_world;
  CGSize size;
  b2Body *ground;
  b2Body *terrain;
}

- (void)createGroundWithWorld:(b2World*)world withSize:(CGSize)terrainSize;
- (void)generateTerrainWithStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint;
- (void)destroy;

@end
Replace Terrain.mm with the following:
#import "Terrain.h"

@implementation Terrain

- (void)createGroundWithWorld:(b2World*)world withSize:(CGSize)terrainSize
{
  _world = world;
  size = terrainSize;
  
  b2BodyDef bd;
  bd.position.Set(0.0, 0.0);
  
  // b2Body *ground
  ground = _world->CreateBody(&bd);
  b2PolygonShape shape;
  b2FixtureDef fd;
  fd.shape = &shape;
  fd.density = 0.0;
  fd.friction = 0.3;
  
  // bottom
  shape.SetAsEdge(b2Vec2(0.0, 0.0), b2Vec2(size.width/PTM_RATIO, 0.0));
  ground->CreateFixture(&fd);
  // left
  shape.SetAsEdge(b2Vec2(0.0, 0.0), b2Vec2(0.0, size.height/PTM_RATIO));
  ground->CreateFixture(&fd);
  // top
  shape.SetAsEdge(b2Vec2(0.0, size.height/PTM_RATIO), 
                  b2Vec2(size.width/PTM_RATIO, size.height/PTM_RATIO));
  ground->CreateFixture(&fd);
  //right
  shape.SetAsEdge(b2Vec2(size.width/PTM_RATIO, size.height/PTM_RATIO), 
                  b2Vec2(size.width/PTM_RATIO, 0.0));
  ground->CreateFixture(&fd);
}

- (void)generateTerrainWithStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint
{
  int vertCount = 30;
  
  float interval = fabs((endPoint.x - startPoint.x))/vertCount;
  
  b2Vec2 vertices[vertCount];
  
  b2BodyDef bd;
  bd.position.Set(0.0, 0.0);
  terrain = _world->CreateBody(&bd);
  b2PolygonShape shape;
  b2FixtureDef fd;
  fd.shape = &shape;
  fd.friction = 3;
  fd.density = 0.0;
  
  for (int i = 0; i < vertCount; i++)
  {
    if (i == 0)
      vertices[i] = b2Vec2(startPoint.x/PTM_RATIO, 0.0);
    else if (i == vertCount -1)
      vertices[i] = b2Vec2(endPoint.x/PTM_RATIO, 0.0);
    else
      vertices[i] = b2Vec2((startPoint.x+interval*i)/PTM_RATIO, (arc4random()%200+20)/PTM_RATIO);
  }
  
  for (int i = 0; i < vertCount-1; i++)
  {
    shape.SetAsEdge(vertices[i], vertices[i+1]);
    terrain->CreateFixture(&fd);
  }
}

- (void)destroy
{
  _world->DestroyBody(terrain);
  _world->DestroyBody(ground);
}

- (void)dealloc
{
  [super dealloc];
}

@end

We have truck and terrains now, just add them to the game layer. Open up the Classes folder and click on HelloWorldLayer.h, and replace it with the following:
#import "cocos2d.h"
#import "Box2D.h"
#import "GLES-Render.h"

#import "MonsterTruck.h"
#import "Terrain.h"

#define PTM_RATIO 32.0f

// HelloWorldLayer
@interface HelloWorldLayer : CCLayer
{
  b2World *_world;
  GLESDebugDraw *_debugDraw;
  
  CGPoint startPoint, endPoint;
  CGSize terrainSize;
  
  MonsterTruck *_truck;
  Terrain *_terrain;
}

// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;

@end
Open HelloWorldLayer.mm and add the following methods right before init method
- (void)createWorld
{
  b2Vec2 gravity = b2Vec2(0.0, -10.0);
  bool doSleep = true;
  _world = new b2World(gravity, doSleep);
  _world->SetContinuousPhysics(true);
}

- (void)setDebugDraw
{
  _debugDraw = new GLESDebugDraw(PTM_RATIO);
  uint32 flags = 0;
  flags += 1 * b2DebugDraw::e_shapeBit;
  flags += 1 * b2DebugDraw::e_jointBit;
  // flags += 1 * b2DebugDraw::e_aabbBit;
  // flags += 1 * b2DebugDraw::e_pairBit;
  // flags += 1 * b2DebugDraw::e_centerOfMassBit;
  _debugDraw->SetFlags(flags);
  _world->SetDebugDraw(_debugDraw);
}
We don't need debug draw enabled commonly, but I don't have textures so I have to enable it in order to see what I have done.

Replace init method with the following:
-(id) init
{
  // always call "super" init
  // Apple recommends to re-assign "self" with the "super" return value
  if( (self=[super init])) 
  {
    [[CCEventDispatcher sharedDispatcher] addKeyboardDelegate:self priority:0];
    
    // Craete a new world
    [self createWorld];
    
    // set debug draw
    [self setDebugDraw];
    
    CGSize winSize = [CCDirector sharedDirector].winSize;
    
    terrainSize = CGSizeMake(winSize.width * 20, winSize.height * 10);
    
    startPoint = ccp(150, 150);
    endPoint = ccp(terrainSize.width-150, 150);
    
    // create terrain
    _terrain = [Terrain node];
    [self addChild:_terrain];
    [_terrain createGroundWithWorld:_world withSize:terrainSize];
    [_terrain generateTerrainWithStartPoint:ccp(300, 0) endPoint:ccp(terrainSize.width-300, 0)];
    
    _truck = [MonsterTruck node];
    [self addChild:_truck];
    [_truck createTruckWithWorld:_world withPosition:startPoint];
    
    [self runAction:[CCFollow 
                     actionWithTarget:_truck 
                     worldBoundary:CGRectMake(0, 0, terrainSize.width, terrainSize.height)]];
    
    [self schedule:@selector(tick:)];
  }
  return self;
}
then add tick: method and draw method so that we can see the dynamic truck.
- (void)tick:(ccTime)dt
{  
  //It is recommended that a fixed time step is used with Box2D for stability
  //of the simulation, however, we are using a variable time step here.
  //You need to make an informed choice, the following URL is useful
  //http://gafferongames.com/game-physics/fix-your-timestep/
  
  // Instruct the world to perform a single step of simulation. It is
  // generally best to keep the time step and iterations fixed.

  _world->Step(1.0/60.0, 30, 30);
  // update the springs of the truck
  [_truck updateSprings];
}

- (void)draw
{
  // Defaut GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
  // Needed states: GL_VERTEX_ARRAY,
  // Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
  glDisable(GL_TEXTURE_2D);
  glDisableClientState(GL_COLOR_ARRAY);
  glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  
  _world->DrawDebugData();
  
  glEnable(GL_TEXTURE_2D);
  glEnableClientState(GL_COLOR_ARRAY);
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
Build and run the project, we can the a truck-like box on the screen. It's ok except that we can't control it. Oops, I forget to handle the key events.
// up: accelerate
// down: brake
// left: lean left
// right: lean right
// space: restart

- (BOOL)ccKeyDown:(NSEvent *)event
{
  if ([event modifierFlags] & NSNumericPadKeyMask)  // arrow keys have this mask
  {
    NSString *theArrow = [event charactersIgnoringModifiers];
    unichar keyChar = 0;
    if ([theArrow length] == 0)
      return YES; // reject dead keys
    if ([theArrow length] == 1)
    {
      keyChar = [theArrow characterAtIndex:0];
      if (keyChar == NSLeftArrowFunctionKey) 
      {
        CCLOG(@"Left Arrow pressed");
        [_truck leftArrowPressed];
        return YES;
      }
      if (keyChar == NSRightArrowFunctionKey)
      {
        CCLOG(@"Right Arrow pressed");
        [_truck rightArrowPressed];
        return YES;
      }
      if (keyChar == NSUpArrowFunctionKey) 
      {
        CCLOG(@"Up Arrow pressed");
        [_truck upArrowPressed];
        return YES;
      }
      if (keyChar == NSDownArrowFunctionKey)
      {
        CCLOG(@"Down Arrow pressed");
        [_truck downArrowPressed];
        return YES;
      }
    }
  }
  return NO;
}

- (BOOL)ccKeyUp:(NSEvent *)event
{
  if ([event modifierFlags] & NSNumericPadKeyMask)  // arrow keys have this mask
  {
    NSString *theArrow = [event charactersIgnoringModifiers];
    unichar keyChar = 0;
    if ([theArrow length] == 0)
      return YES; // reject dead keys
    if ([theArrow length] == 1)
    {
      keyChar = [theArrow characterAtIndex:0];
      if (keyChar == NSLeftArrowFunctionKey || keyChar == NSRightArrowFunctionKey) 
      {
        CCLOG(@"Left Arrow released");
        [_truck leftRightArrowReleased];
        return YES;
      }
      if (keyChar == NSUpArrowFunctionKey || keyChar == NSDownArrowFunctionKey) 
      {
        CCLOG(@"Up Or Down Arrow released");
        [_truck upDownArrowReleased];
        return YES;
      }
    }
  }
  else if ([event modifierFlags])  // arrow keys have this mask
  {
    NSString *theArrow = [event charactersIgnoringModifiers];
    unichar keyChar = 0;
    if ([theArrow length] == 0)
      return YES; // reject dead keys
    if ([theArrow length] == 1)
    {
      keyChar = [theArrow characterAtIndex:0];
      if (keyChar == 0x20) // space bar
      {
        CCLOG(@"space bar hitted!");
        [_truck destroy];
        [_terrain destroy];
        [_terrain createGroundWithWorld:_world withSize:terrainSize];
        [_terrain generateTerrainWithStartPoint:ccp(300, 0) 
                                       endPoint:ccp(terrainSize.width-300, 0)];
        [_truck createTruckWithWorld:_world withPosition:startPoint];
        return YES;
      }
    }
  }
  return NO;
}
Now we can control the truck using arrow keys and reset the layer by hitting space bar.

Don't forget the dealloc method before @end
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
  // in case you have something to dealloc, do it in this method
  // in this particular example nothing needs to be released.
  // cocos2d will automatically release all the children (Label)
  
  delete _world;
  _world = NULL;
  delete _debugDraw;
  
  // don't forget to call "super dealloc"
  [super dealloc];
}
If you change the scale of HelloWorldLayer instance in the scene method, you may not follow the truck correctly by using CCFlow. I'm just a translator and don't know how to solve the problem.

9/06/2011

How To Build A Distributed Git Repository With Dropbox

Version control is used commonly in software development. It's helpful and essential, especially in teamwork. There are may version control systems such as Subversion, hg, and VSS. Here I'm going to use Git which is powerful and easy to use with Dropbox to create a distributed repository.
Before we start, make sure that you have Git and Dropbox installed on your computer.
  1. Make Project directory a Git repository and commit Project.
    $ cd ~/workspace/Project
    $ git init
    $ git add .
    $ git commit -m "The first commit of Project: Initialize the repository"
    
    Now we have an .git directory which contains the reversion information under Project directory.
  2. Then switch to your Dropbox directory and create a new folder. Make a bare repository with Project in the folder created just now.
    cd ~/Dropbox
    $ mkdir repository
    $ cd repository
    $ git clone --bare ~/workspace/Project Project.git
    
  3. We can remove the Project under workspace directory now and get a clone from our Dropbox repository.
    $ cd ~/workspace
    $ rm -f -r Project
    $ git clone ~/Dropbox/repository/Project.git
    
  4. Share your repository folder with your coworkers.

We have a distributed repository now. It's simple, right?

BTW, if you are not using Dropbox, you can try github, it's free for hosting open source projects.

Two configure files for Xcode projects that you may need. :-)
  • .gitignore
    # old skool
    #.svn
    #.hg
    #CVS
    
    # Mac OS X noise
    *.DS_Store
    *.swp
    *~.nib
    profile
    
    # Xcode noise
    *.pbxuser
    *.perspective
    *.perspectivev3
    *.mode1
    *.mode1v3
    *.mode2v3
    
    # Xcode4 noise
    xcuserdata
    *.xcuserstate
    
    # Generated files
    MANIFEST
    build/
    dist/
    *.pyc
    *.[oa]
    
    # Textmate - if you build your xcode projects with it
    *.tm_build_errors
    
  • .gitattributes
    *.pbxproj -crlf -diff -merge