How to move a body manually in Box2D? or Give a force to a body in Box2D, iPhone.

This is a sample code to move a body in Box2D .
First you have to make a body with variable name “moving_rec” and call the below function in a schedular at regular intervals.

-(void) moveBody{
       b2Vec2 force = b2Vec2(0,0);
       force = b2Vec2(0,3);       //Giving the x an y to negative will move the body in opposite direction.
       moving_rec->SetLinearVelocity(force); //set Linear velocity for moving in a constant speed.
}

Please leave your comments on this post.

Collision detection in Box2D

Hi,

Collision can be detected simply using the following lines of code with box2D.

if((contact.fixtureA == aimFixture && contact.fixtureB == tarFixture) ||
     (contact.fixtureA == tarFixture&& contact.fixtureB == aimFixture ))
     {
        NSLog(@"Collision between aim fixture and target fixture detected!");
     }

Here aimFixture & tarFixture are two custom fixtures whose collision you want to find out.
:)

How to add sprite to a body in Box2D in Adobe AIR, FLEX and FLASH? Or Add image/Sprite to a body in ActionScript.

The below code is for FlashBuilder 4, If you are using FlexBuilder3 use addChild()
instead of the commented block in the following code.

public function addCircle(){x:Number, y: Number, radius:Number, ballcip:Ball):void{

bd:b2BodyDef = new b2BodyDef();

      var loader:Loader = new Loader();

      loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,
                                                           imageFailed);
      var request:URLRequest = new URLRequest("ball.png");
      loader.load(request);

      /*optionally change the position of the image if not fitting in the body */
      /* You can also rotate the image.*/
      loader.x = -50;
      loader.y = -50;

      /***************************************/
      var ui:UIComponent = new UIComponent();
      ui.addChild(loader);
      this.addElement(ui);
      /**************************************/

      bd.userData = ui;
      bd.position.Set(_x/m_phys_scale, _y/ m_phys_scale);
      bd.type=b2Body.b2_dynamicBody;
      var ball_shape:b2CircleShape=new b2CircleShape(50/world_scale);
      var ball_fixture:b2FixtureDef = new b2FixtureDef();
      ball_fixture.shape=ball_shape;
      ball_fixture.friction=0.9;
      ball_fixture.density=30;
      ball_fixture.restitution=0.3;
      ball_body=world.CreateBody(bd);
      ball_body.CreateFixture(ball_fixture);
}

private function imageFailed(event:IOErrorEvent):void
{
      Alert.show("Image loading failed"); //make sure you have the image.
}

Creating Menu in Iphone Cocos2D or Box2D?

Use CCMenuItemSprite and CCMenu in iPhone to create menu.

-(void) setUpMenu
{
	 CCSprite *Home1 = [CCSprite spriteWithFile:@"Home1.png"];
	 CCSprite *Home2 = [CCSprite spriteWithFile:@"Home1.png"];
	 Home2.opacity = 100;

	 CCSprite *Levels1 = [CCSprite spriteWithFile:@"levels2.png"];
	 CCSprite *Levels2 = [CCSprite spriteWithFile:@"levels2.png"];
	 Levels2.opacity = 100;

	 CCSprite *Refresh1 = [CCSprite spriteWithFile:@"refresh.png"];
	 CCSprite *Refresh2 = [CCSprite spriteWithFile:@"refresh.png"];
	 Refresh2.opacity = 100;

	 CCSprite *go_back1 = [CCSprite spriteWithFile:@"back2.png"];
	 CCSprite *go_back2 = [CCSprite spriteWithFile:@"back2.png"];
	 go_back2.opacity = 100;

	 CCMenuItemSprite  *top_menuSprite1 = [CCMenuItemSprite itemFromNormalSprite:Home1 selectedSprite:Home2 target:self selector:@selector(goHome)];
	 CCMenuItemSprite  *top_menuSprite2 = [CCMenuItemSprite itemFromNormalSprite:Levels1 selectedSprite:Levels2 target:self selector:@selector(goToLevelSelection)];
	 CCMenuItemSprite  *top_menuSprite3 = [CCMenuItemSprite itemFromNormalSprite:Refresh1 selectedSprite:Refresh2 target:self selector:@selector(reloadGame)];
	 CCMenuItemSprite  *top_menuSprite4 = [CCMenuItemSprite itemFromNormalSprite:go_back1 selectedSprite:go_back2 target:self selector:@selector(menuGoBack)];
	 top_menu = [CCMenu menuWithItems:top_menuSprite1,top_menuSprite2, top_menuSprite3 ,top_menuSprite4, nil];
	 [top_menu  alignItemsVerticallyWithPadding:10.0f];
	 top_menu.position = ccp(240,160);

	 [self addChild:top_menu z:2];
}

call this function to set up the menu for your home page in your iPhone game or you can change this code directly to ANDROID and it will work.
Make sure you have all the images mentioned in the above example.
This menu will appear on the centre of the screen in Landscape mode.

How to remove forces applied in Box2D bodies ?

Hi,

For removing the forces applied to your Box2D bodies, use the following line of code.

yourWorld->ClearForces();

Here ‘yourWorld’ is the your box2D world.
:)

Destroying Box2D Physics Bodies in Corona SDK

Hi,

For destroying physics bodies in Corona SDK, use any of the following methods.

urBody:removeSelf()

OR

urBody.parent:remove( urBody )

Note :
While Box2D objects will be safely retained until the end of the current world step, their Lua references will be deleted immediately. Therefore, be careful not to accidentally delete the same Lua object more than once. This situation could occur when deleting objects involved in collisions, which can potentially have many event phases before the collision is fully resolved. The solution is simple:

local function onCollision( self, event )
        if ( event.phase == "began" ) then

                -- Check if body still exists before removing!
                if ( urBody ) then
                        urBody:removeSelf()
                        urBody = nil
                end

        end
end

:)

How to detect single/double/triple taps in iPhone ?

Hi,
How can you detect single/double/triple taps in iPhone using Objective C?
Use the following code to detect single or multiple taps in iPhone/iPad/iPod.
The code can also be used with Cocos2D & Box2D.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *urtouch = [touches anyObject];

    NSUInteger urtapCount = [urtouch tapCount];

    switch (urtapCount) {

       case 1:
         NSLog(@"Single Tap Detected!");
          break;

       case 2:
          NSLog(@"Double Tap Detected!");
          break;

       case 3:
        NSLog(@"Triple Tap Detected!");
        break;

      default :
       break;

   }
}

Try it out! You can even detect Quadrup! :)

Identifying sprite associated with a particular body in Box2D

Hi,

How can you identify the sprite associated with a particular body while using box2D ? Sometimes you may need to identify the sprite associated with the body you are using. For that use the following line of code.

CCSprite *yourSprite= (CCSprite*)yourBody->GetUserData();

Now you got the corresponding sprite in your ‘yourSprite’
:)

How to detect shake in iPhone ? An example

Hi,
Sometimes you may want to detect shake gesture in iPhone using your programs. But how can you detect shake gesture in iPhone? Shake gesture in iPhone can be detected by using the accelerometer. The following lines of code can be used for detecting the shake gesture in iPhone. You can use these lines of code in your cocos2D applications/games.

First of all you MUST enable accelerometer in the init function

isAccelerometerEnabled = YES;

Then use the following function to detect the shake gesture.

- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
    if(abs(acceleration.x-oldX )>0.7 || abs(acceleration.y-oldY)>0.7)
   {
       NSLog(@”Yupie! Shake detected!”);
   }
oldX = acceleration.x;
oldY = acceleration.y;
}

Here oldX & oldY are variables that store accelerometer values and 0.7 is the value you are giving to check for shake gesture. That’s it. :)

How to remove box2D body from world ?

Hi,
If you are a game developer and you are using box2D for real world simulations, you would probably need a particular body to be removed from the box2D world! But how can you remove box2D body from world ? See the following sample code which does the same.

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

//Getting Touch Locations
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];

//Converting to cocos2D positioning
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);

     //Getting body list from world
     for (b2Body* b = world->GetBodyList(); b; b = b->GetNext()) {
          //Getting Fixture from the bodies
          b2Fixture *bf1 = b->GetFixtureList();
          //Checking whether the fixture contains touch location!
          if (bf1->TestPoint(locationWorld)) {
             //If YES assigning user data to a sprite tempSprite
             CCSprite *tempSprite = (CCSprite *) b->GetUserData();
             //Checking whether the user data sprite tag is 7
             if (tempSprite .tag==7) {
                //If YES then remove the sprite & the body!
                [self removeChild:tempSprite cleanup:YES];
                world->DestroyBody(b);
             }
        }
    }
}

Here tag 7 is what we previously assigned for the sprite corresponding to the body’s user data!

How to prevent collision between connected bodies in Box2D ?

Hi,

While using Box2D , in many cases you may need to connect two bodies together. But the collision between them during motion is not what you preferred! So how can you prevent those bodies being connected in Box2D from collision?
Use the line of code to prevent the collision.

jointDef.collideConnected = false;

How to play music in cocos2D or Box2D, iPhone?

This simple code plays a music……..


[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@”my_music.mp3″];

For stopping the music use this…….


[[SimpleAudioEngine sharedEngine]stopBackgroundMusic];

To pause the music use this line of code…..


[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];

How to make gear joint in Box2D, iPhone?

Gear joints are one of the real specialities of Box2D.

By creating gear joints between two bodies you can actually simulate a real world gear. For creating a gear joint you need two bodies connected by a revolute or prismatic joint.

The below code creates two bodies in the shape of a circle which is actually attached to the ground. however you can also create joints without joining it with the ground. Here you have to make a ground with possible four fixtures or no fixtures simply creating a body.


        b2Body* body1 = circle1;
        b2Vec2 pos1 = circle1 -> GetPosition();//get position of first body.....
        b2Body* body2 = circle2;
        b2Vec2 pos2 = circle2 -> GetPosition(); // get position of second body....
        revJointDef.Initialize(ground, circle1, pos1);
        b2RevoluteJointDef revJointDef2;
        revJointDef2.Initialize(ground, body2, pos2)//revolute joint is initialized
        joint1 = world->CreateJoint(&revJointDef;); //First joint.....
        revJointDef2.maxMotorTorque = 20000.000000f; //connect a motor to the joint2
        revJointDef2.motorSpeed = 120.000000f / 60; //set the rotation speed.....
        revJointDef2.enableMotor = true;            // enable the motor.....
        joint2 = world->CreateJoint(&revJointDef2;);  //Second joint.....

        gearJointDef.bodyA = body1;
        gearJointDef.bodyA = body2;
        gearJointDef.joint1 = joint1;
        gearJointDef.joint2 = joint2;
        gearJointDef.collideConnected = true;
        gearJointDef.ratio = circleShape2.m_radius/circleShape1.m_radius;
        world->CreateJoint(&gearJointDef;); // this line creates the joint.

Please leave your valuable comments……………………..

Collision Detection In Box2D – Using With Cocos2D

For an interactive game building using Box2D, collision detection of Box2D bodies is necessary. There is an easy way to implement collision detection in Box2D.

For checking whether two bodies have collided with each other in Box2D while using it with cocos2D, then use the following lines of code where ever you want to check collision.

if((contact.fixtureA == sourceFixture && contact.fixtureB == destinationFixture) ||
(contact.fixtureA == destinationFixture && contact.fixtureB == sourceFixture ))
{
//What you want to do after checking the collision?!!!
//That lines of code goes here!
//Simple and Pretty , isn't it?
}

Here you are cheking whether two box2D fixtures are in contact or not! And you can decide which fixtures you need to check for collision.
:)

Removing Forces From Your World in Box2D Cocos2D

Hi,

In certain situations you may need to remove all the forces you have applied on different bodies in your box2D world.
Then what to do?
Removing all the forces from the bodies in the box2D world is simple. Just use the single line of code.

yourWorld->ClearForces();

Here yourWorld is your Box2D world. Simple, isn’t it?
:)

Create a polygon in Flash or Adobe AIR using Box2D.

The below function creates a polygon in the shape of a triangle.
Please call the debugdraw function inside your update method to view the results.
Make sure you import the Box2D classes into your file.

public function init():void
{
	 debug_draw();
	 addEventListener(Event.ENTER_FRAME, update);
	 createTriangle();
}


 public function createTriangle():void
 {
	 var fd : b2FixtureDef = new b2FixtureDef();
	 var initVel : b2Vec2 = new b2Vec2();
	 var bodyDef:b2BodyDef= new b2BodyDef();
	 var shape : b2PolygonShape = new b2PolygonShape();
	 bodyDef.type = b2Body.b2_dynamicBody;
	 bodyDef.position.Set(4.446215, 3.649402);
	 bodyDef.angle = 0.000000;
	 var polygon1 : b2Body = world.CreateBody(bodyDef);
	 initVel.Set(0.000000, 0.000000);
	 polygon1.SetLinearVelocity(initVel);
	 polygon1.SetAngularVelocity(0.000000);

	 var arr : Vector. = new Vector.();
	 arr[0] = new b2Vec2(-0.980080, 2.374502);
	 arr[1] = new b2Vec2(-0.980080, -1.187251);
	 arr[2] = new b2Vec2(1.960159, -1.187251);
	 shape.SetAsVector(arr,3);
	 fd.shape = shape;
	 fd.density = 0.30;
	 fd.friction = 0.300000;
	 fd.restitution = 0.600000;
	 fd.filter.groupIndex = 0;
	 fd.filter.categoryBits = 65535;
	 fd.filter.maskBits = 65535;
	 polygon1.CreateFixture(fd);
}


public function debug_draw():void
{
	 var debug_draw:b2DebugDraw = new b2DebugDraw();
	 var debug_sprite:Sprite = new Sprite();

	 /** Use this instead of addChild() ********/

	 var ui:UIComponent = new UIComponent();
	 ui.addChild(debug_sprite);
	 this.addElement(ui);

	 /*****************************************/
	 //addChild(debug_sprite);
	 debug_draw.SetSprite(debug_sprite);
	 debug_draw.SetDrawScale(world_scale);
	 debug_draw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
	 debug_draw.SetFillAlpha(0.5);
	 world.SetDebugDraw(debug_draw);
}

public function update(e:Event) : void
{
	 //We need to do this to simulate physics

	 world.Step(m_timestep,m_iterations,10);
	 for (var bb:b2Body=world.GetBodyList(); bb; bb=bb.GetNext())
	 {
		 if (bb.GetUserData() is Sprite)
		 {
			 bb.GetUserData().x=bb.GetPosition().x * 30;
			 bb.GetUserData().y=bb.GetPosition().y * 30;
			 bb.GetUserData().rotation=bb.GetAngle() * 180 / Math.PI;
		 }
	 }
	 world.DrawDebugData();
}

How to Implement Box2D in Adobe AIR?

Everyone will be fascinated how flash games are built on the web that implements the real world physics. Well for your information there are a lot of physics engines available.
One of them is the Box2D. Box2D was written in C++. Then it was converted to flash.

So now I am going to show you how to build these games on your desktop.
For this you need the Adobe Flashbuilder 4.
Download it from here http://www.adobe.com/products/flashbuilder/
And follow these steps.

1. First you have to download the Box2D library for flash.
2. Create a Flex Project for the desktop(i.e for Adobe AIR) and name it “Test”.
3. Create a folder named libs inside the project folder.
4. Right click on the libs and import the downloaded Box2D swc into it.
Or Right click on the project folder and click properties, add swc folder named libs which
contains your Box2D library for flash. After that a folde named “Referenced Libraries” will
appear.
See the figure below.

Now right click on the project folder and new-> Actionscript class-> name it “Ball” and press enter. A file named Ball.as will be created. Now copy the following code to this file.

/************************************** Ball.as ***********************************/

package
{
 import flash.display.Sprite;
 import flash.geom.Matrix;
 import mx.controls.Alert;

 public class Ball extends Sprite
 {
 private var mc:Sprite;
 public function Ball(radius:Number, color:Number = 0x660033)
 {
 super();
 mc = new Sprite();
 setRegistrationPoint( mc, mc.width >> 1, mc.height >> 1, true);
 mc.graphics.lineStyle(1, 0x000000);
 mc.graphics.beginFill(color);
 mc.graphics.drawCircle(0, 0, radius);
 mc.graphics.endFill();

 addChild(mc);
 }
 public function setRegistrationPoint(s:Sprite, regx:Number, regy:Number, showRegistration:Boolean) : void
 {
 s.transform.matrix = new Matrix(1, 0, 0, 1, -regx, -regy);
 if (showRegistration)
 {
 var mark:Sprite = new Sprite();
 mark.graphics.lineStyle(1, 0x000000);
 mark.graphics.moveTo(-5, -5);
 mark.graphics.lineTo(5, 5);
 mark.graphics.moveTo(-5, 5);
 mark.graphics.lineTo(5, -5);
 s.addChild(mark);
 }
 }
 }
}

Now copy the below code to Test.MXML

    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="init()">


   import mx.controls.Alert;
   import mx.core.UIComponent;
   import flash.display.Sprite;
   import flash.events.Event;
   import flash.events.MouseEvent;
   import flash.display.Stage;
   import Box2D.Dynamics.*;
   import Box2D.Collision.*;
   import Box2D.Collision.Shapes.*;
   import Box2D.Common.Math.*;

   public var the_ball:Ball;
   public var main:Main;
   public var m_dbgSprite:Sprite;
   public var m_world:b2World;
   public var m_phys_scale:Number = 30;
   public var m_timestep:Number = 1.0/30.0;
   public var m_iterations:N umber = 10.0;

   //initial box coordinates when we first press mouse down
   public var initX:Number = 0.0;
   public var initY:Number = 0.0;
   public var drawing:Boolean = false;
   public var b:b2Body;
   private var colorArray:Array = new Array(0xFFFF33, 0xFFFFFF, 0x79DCF4, 0xFF3333, 0xFFCC33, 0x99CC33);

   public function init():void{

    var gravity:b2Vec2 = new b2Vec2(0,9.8);
    var worldAABB:b2AABB = new b2AABB();
    worldAABB.lowerBound.Set(-1000,-1000);
    worldAABB.upperBound.Set(1000,1000);
    m_world = new b2World(worldAABB,gravity,true);

    //Add our ground and walls
    addStaticBox(250/m_phys_scale,510/m_phys_scale,250/m_phys_scale,10/m_phys_scale);
    addStaticBox(250/m_phys_scale,-10/m_phys_scale,250/m_phys_scale,10/m_phys_scale);
    addStaticBox(-10/m_phys_scale,250/m_phys_scale,10/m_phys_scale,250/m_phys_scale);
    addStaticBox(510/m_phys_scale,250/m_phys_scale,10/m_phys_scale,250/m_phys_scale);

    addEventListener(Event.ENTER_FRAME, update);
    stage.addEventListener(MouseEvent.MOUSE_DOWN,mousePressed);
    stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoved);
    stage.addEventListener(MouseEvent.MOUSE_UP,mouseReleased);

    var dbgDraw:b2DebugDraw = new b2DebugDraw();
    var dbgSprite:Sprite = new Sprite();
    var ui:UIComponent = new UIComponent();
    ui.addChild(dbgSprite);
    this.addElement(ui);
    //addChild(dbgSprite);
    dbgDraw.m_sprite = dbgSprite;
    dbgDraw.m_drawScale = 20.0;
    dbgDraw.m_fillAlpha = 0.0;
    dbgDraw.m_lineThickness = 1.0;
    //dbgDraw.m_drawFlags = 0xFFFFFFFF;
    //dbgDraw.m_drawFlags=b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit|b2DebugDraw.e_coreShapeBit|b2DebugDraw.e_aabbBit|b2DebugDraw.e_obbBit|b2DebugDraw.e_pairBit|b2DebugDraw.e_centerOfMassBit;

    m_world.SetDebugDraw(dbgDraw);
   }
   public function mousePressed(e:MouseEvent) : void {
    //Store initial X and Y position
    initX = e.localX;
    initY = e.localY;

    var randomColorId:Number = Math.floor(Math.random()*colorArray.length);

    the_ball = new Ball(50, colorArray[randomColorId]);

    the_ball.x = mouseX;
    the_ball.y = mouseY;
    the_ball.width = 1;
    the_ball.height = 1;
    var ui:UIComponent = new UIComponent();
    ui.addChild(the_ball);
    this.addElement(ui);

    drawing = true;
   }
   public function mouseMoved(e:MouseEvent) : void {
    if (drawing) {
     the_ball.x = mouseX;
     the_ball.y = mouseY;
    }
   }
   public function mouseReleased(e:MouseEvent) : void {
    drawing = false;
    addCircle( mouseX,  mouseY, the_ball.width/2,the_ball);
   }
   public function addCircle(_x:Number, _y:Number, _radius:Number, ballclip:Ball) : void {
    var bd:b2BodyDef = new b2BodyDef();
    var cd:b2CircleDef = new b2CircleDef();
    var area:Number = Math.floor(_radius*_radius*Math.PI/25)/100;

    cd.radius = Math.abs(_ra dius)/m_phys_scale;
    cd.density = 2;
    cd.restitution = 0.7;
    cd.friction = 2;
    bd.position.Set(_x/m_phys_scale, _y/ m_phys_scale);
    bd.userData = ballclip;
    b = m_world.CreateBody(bd);
    b.CreateShape(cd);
    b.SetMassFromShapes();
   }
   public function addStaticBox(_x:Number,_y:Number,_halfwidth:Number,_halfheight:Number) : void {
    var bodyDef:b2BodyDef = new b2BodyDef();
    bodyDef.position.Set(_x,_y);
    var boxDef:b2PolygonDef = new b2PolygonDef();
    boxDef.SetAsBox(_halfwidth,_halfheight);
    boxDef.density = 0.0;
    var body:b2Body = m_world.CreateBody(bodyDef);
    body.CreateShape(boxDef);
    body.SetMassFromShapes();
   }
   public function update(e:Event) : void {
    //We need to do this to simulate physics
    if (drawing) {
     the_ball.width+=2;
     the_ball.height+= 2;
    }
    m_world.Step(m_timestep,m_iterations);
    for (var bb:b2Body=m_world.m_bodyList; bb; bb=bb.m_next) {
     if (bb.m_userData is Sprite) {
      bb.m_userData.x=bb.GetPosition().x * 30;
      bb.m_userData.y=bb.GetPosition().y * 30;
      bb.m_userData.rotation=bb.GetAngle() * 180 / Math.PI;
     }
    }
   }
  ]]>
 

If you have errors that you can’t find in your file then go to window-> problems. Look for the problem.
If the problem is about the SDK . then right click on the project folder and properties and change the default SDK to FLEX 4.

How to Create a pin-Joint on a body in Box2D iphone?

Here mybody is a body to which I am connecting a pinpoint.
The pin joint is between the world and the body. So it will appear as hanging in the wall if the gravity is downwards. ‘The ground’ is the other body to which the my_body is connected.
First you create a big ground body with 3 or more fixtures and try this.
Happy coding.

//myBody
bodyDef.position.Set(10.920371f, 6.620342f);
bodyDef.userData = my_sprite;
bodyDef.angle = 0.000000f;
b2Body* myBody = world->CreateBody(&bodyDef;);
initVel.Set(0.000000f, 0.000000f);
myBody->SetLinearVelocity(initVel);
myBody->SetAngularVelocity(0.000000f);

b2Vec2 myBody_vertices[4];
myBody_vertices[0].Set(-2.245807f, -0.266091f);
myBody_vertices[1].Set(2.245807f, -0.266091f);
myBody_vertices[2].Set(2.245807f, 0.266091f);
myBody_vertices[3].Set(-2.245807f, 0.266091f);
shape.Set(myBody_vertices, 4);
fd.shape = &shape;
fd.density = 0.015000f;
fd.friction = 0.300000f;
fd.restitution = 0.600000f;
fd.filter.groupIndex = int16(0);
fd.filter.categoryBits = uint16(65535);
fd.filter.maskBits = uint16(65535);

myBody->CreateFixture(&fd;);


//Revolute joints - creating the pin joint.
pos.Set(8.940655f, 6.620342f);
revJointDef.Initialize(myBody, ground, pos);
revJointDef.collideConnected = false;
world->CreateJoint(&revJointDef;);

Here mybody is a body to which I am connecting a pinpoint.
The pin joint is between the world and the body. So it will appear as hanging in the wall if the gravity is downwards. ‘The ground’ is the other body to which the my_body is connected.
First you create a big ground body with 3 or more fixtures and try this.
Happy coding.

//myBody
bodyDef.position.Set(10.920371f, 6.620342f);
bodyDef.userData = my_sprite;
bodyDef.angle = 0.000000f;
b2Body* myBody = world->CreateBody(&bodyDef;);
initVel.Set(0.000000f, 0.000000f);
myBody->SetLinearVelocity(initVel);
myBody->SetAngularVelocity(0.000000f);

b2Vec2 myBody_vertices[4];
myBody_vertices[0].Set(-2.245807f, -0.266091f);
myBody_vertices[1].Set(2.245807f, -0.266091f);
myBody_vertices[2].Set(2.245807f, 0.266091f);
myBody_vertices[3].Set(-2.245807f, 0.266091f);
shape.Set(myBody_vertices, 4);
fd.shape = &shape;
fd.density = 0.015000f;
fd.friction = 0.300000f;
fd.restitution = 0.600000f;
fd.filter.groupIndex = int16(0);
fd.filter.categoryBits = uint16(65535);
fd.filter.maskBits = uint16(65535);

myBody->CreateFixture(&fd;);


//Revolute joints - creating the pin joint.
pos.Set(8.940655f, 6.620342f);
revJointDef.Initialize(myBody, ground, pos);
revJointDef.collideConnected = false;
world->CreateJoint(&revJointDef;);

How will you check whether you have touched a body in Box2D?

You can iterate through all bodies in the world and check whether you have touched a particular body.
You can get all the userdata from the current body
The userdata contains the width, height, sprite etc.
Just Log the userdata in the current body to see all these.

 for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
 {
  b2Fixture *bf = b->GetFixtureList(); // Get the fixture of current body.
  CCSprite *temp_sprite =(CCSprite *) b->GetUserData();// Got the sprite in that body.
  if(temp_sprite!=NULL){  // Checking if the body has a sprite.

   if (bf->TestPoint(locationWorld))
   {
    NSLog(@"Hooray I touched the body");

    if (temp_sprite.tag==10)
    {
      //do something…..
    }

   }}

 }

How to implement a bomb explosion in Box2D iphone?

Below code is a simplest way to do that.

-(void) explodeBomb
	{
		b2Vec2 force = b2Vec2(0.25,0.70); // give the direction for the force.
		bombBody->ApplyLinearImpulse(force, bombBodyDef.position);
		CCSprite *sp = (CCSprite *) bombBody->GetUserData();
		sp.opacity = 0; // setting the sprite in the body opacity to zero.
		[self schedule:@selector(destroyBomb) interval:2]; //destroying bombBody after 2 sec.
	}
	-(void) destroyBomb
	{
		CCLOG(@"Destroying Bomb");
		world->DestroyBody(bombBody);
	}

How to check whether you have touched a body in Box2D iPhone?

You can check it by using the TestPoint function available for the Fixtures.

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch *myTouch = [touches anyObject];
	CGPoint location = [myTouch locationInView:[myTouch view]];
	location = [[CCDirector sharedDirector] convertToGL:location];
	b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
	for (b2Body *b = world->GetBodyList(); b; b = b->GetNext())
	{

		b2Fixture *f = b->GetFixtureList();
		CCSprite *sprite =(CCSprite *) b->GetUserData();

		if(sprite != NULL)
		{ //Here there should be a userData (sprite) for this to work.
			if(f -> TestPoint(locationWorld))
			{
				NSLog(@"You touched a body");
				if (sprite.tag == 3)
				{
				//do something on touching a specific body.
				}


			}
		}
	}
}

How to shoot a bullet in the direction of touch in Box2D iphone?

write the below code in “ccTouchesBegan” function and you are done.
Here the ballBody represents the bullet body. You can increase the power variable to increase bullet speed.

UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CGPoint shootVector = ccpSub(location, ball.position);
CGFloat shootAngle = ccpToAngle(shootVector);
CGPoint normalizedShootVector = ccpNormalize(shootVector);
CGPoint overshotVector = ccpMult(normalizedShootVector, 420);
CGPoint offscreenPoint = ccpAdd(ball.position, overshotVector);

int power = 100;

b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(ball.position.x/PTM_RATIO, ball.position.y/PTM_RATIO);
ballBodyDef.userData = ball;
b2Body *ballBody = world->CreateBody(&ballBodyDef;);
b2CircleShape circle;
circle.m_radius = 7.0/PTM_RATIO;
float x1 =  cos(shootAngle);
float y1 =  sin(shootAngle);
b2FixtureDef ballShapeDef;
ballShapeDef.shape = &circle;
ballShapeDef.density = 80.0f;
ballShapeDef.friction = 0.0f; // We don't want the ball to have friction!
ballShapeDef.restitution = 1.0f;
ballBody->CreateFixture(&ballShapeDef;);
b2Vec2 force = b2Vec2(x1* power,y1* power);
ballBody->ApplyLinearImpulse(force, ballBodyDef.position);

How to rotate a body manually in Box2D?

The below code helps you to rotate a body in Box2D manually.

-(void) start
{
	rot_sprite = [CCSprite spriteWithFile:[NSString stringWithFormat:@"rot_sprite.png" ]];
	[self addChild: rot_sprite];
	b2BodyDef bodyDef;
	b2Vec2 initVel;
	b2PolygonShape shape;
	b2CircleShape circleShape;
	b2FixtureDef fd;
	b2Body * rotating_body;
	b2RevoluteJointDef revJointDef;
	b2DistanceJointDef jointDef;
	b2Vec2 pos;
	bodyDef.position.Set(11.043825f, 4.984064f);
	bodyDef.angle = 0.000000f;
	bodyDef.userData = rot_sprite;
	rotating_body = world->CreateBody(&bodyDef;);
	initVel.Set(0.000000f, 0.000000f);
	rotating_body->SetLinearVelocity(initVel);
	rotating_body->SetAngularVelocity(0.000000f);
	b2Vec2 rotating_body_vertices[4];
	rotating_body_vertices[0].Set(-0.143426f, -1.565737f);
	rotating_body_vertices[1].Set(0.143426f, -1.565737f);
	rotating_body_vertices[2].Set(0.143426f, 1.565737f);
	rotating_body_vertices[3].Set(-0.143426f, 1.565737f);
	shape.Set(rotating_body_vertices, 4);
	fd.shape = &shape;
	fd.density = 0.015000f;
	fd.friction = 0.300000f;
	fd.restitution = 0.600000f;
	fd.filter.groupIndex = int16(0);
	fd.filter.categoryBits = uint16(65535);
	fd.filter.maskBits = uint16(65535);
	rotating_body->CreateFixture(&fd;);

	        //calling the schedular at intervals to rotate the body.

	[self schedule: @selector(rotateBody) interval:0.01];
}
-(void)rotateBody
{
	angle += 0.02;
	b2Vec2 pos = rotating_body.GetPosition();
	rotating_body.SetTransform(pos, angle);
}

Here the body is named “rotating_body” which is going to rotate and a sprite named “rot_sprite” is it’s userData, please give your own image for it.
Make sure that you have it in your resources otherwise your program will crash.

Note: call this function in a schedular for the body, here-rotating_body to rotate.
Adjust the angle and the schedular-interval for better results.