How to set wallpaper in ANDROID?

Following example shows how to set a Bitmap as wallpaper in ANDROID.
After running this code your wallpaper on the ANDROID phone will change.

Make sure that you have an image named ‘my_wallpaper’ in your drawable folder.

And You have to set this permission in the Manifest.

<uses-permission android:name="android.permission.SET_WALLPAPER"/>
Bitmap wallpaper = BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.my_wallpaper));
    	try
    	{
    			getApplicationContext().setWallpaper(wallpaper);
    	} catch (IOException e)
    	{
    			e.printStackTrace();
    	}

Working with SQLite Database in ANDROID.

Below is a straight forward example of how to deal with SQLite database in ANDROID.
Go ahead and copy and paste the following code to your java file.
The example has one database and performs functions like insert delete and listing of values in a textView.

package com.database;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class databaseactivity extends Activity {
    /** Called when the activity is first created. */

    private static String DBNAME = "mydb.db";
    private static String TABLE = "myTable";

    Button butAdd,butdel;
    EditText nam,mail;
    LinearLayout lay;
    TableLayout layout;
    TextView tev,tev1;
    int f=0;
    Integer ind;
   ScrollView sv;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tev=(TextView)findViewById(R.id.tv);
        tev1=(TextView)findViewById(R.id.tv1);
        layout=(TableLayout)findViewById(R.id.layout);
        lay = (LinearLayout) findViewById(R.id.linear);
        butAdd = (Button) findViewById(R.id.add);
        nam=(EditText)findViewById(R.id.names);
        mail=(EditText)findViewById(R.id.emails);

       SQLiteDatabase mydb;
       mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
       mydb.execSQL("create table if not exists "+TABLE+" (_id integer primary key autoincrement,name text not null,email text not null);");
       mydb.close();
       sv = new ScrollView(this);
       setContentView(sv);
       sv.addView(lay);

       butAdd.setOnClickListener(new View.OnClickListener()
       {
      @Override
      public void onClick(View v)
      {
                  f=0;
                  addTask();
      }
      });
    }

    public void addTask()
    {
                SQLiteDatabase mydb;
                mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
                ContentValues newrow = new ContentValues();
                String a=nam.getText().toString();
                String b=mail.getText().toString();
                if(a.trim().length()!=0 && b.trim().length()!=0)
                {
                                newrow.put("name", nam.getText().toString());
                                newrow.put("email", mail.getText().toString());
                                mydb.insert(TABLE, null, newrow);
                }
                else
                {
                                if(f==0)
                                      Toast.makeText(getApplicationContext(), "Fields cannot be left blank",
                                                                                                               Toast.LENGTH_SHORT).show();
                }
                nam.setText(null);
                mail.setText(null);
                String[] result = new String[]{"_id","name","email"};
                Cursor allrows  = mydb.query(TABLE, result, null, null, null, null, null);
                Integer cindex = allrows.getColumnIndex("name");
                Integer cindex1 = allrows.getColumnIndex("email");
                Integer cindex2 = allrows.getColumnIndex("_id");
                if(allrows.moveToFirst())
                {
                layout.removeAllViews();
                do
                {
                                TableRow row= new TableRow(this);
                                final TextView tv = new TextView(this);
                                final TextView tv1 = new TextView(this);
                                final Button but=new Button(this);
                                but.setText("Delete");
                                final Button butt=new Button(this);
                                butt.setText("Edit");                                ind=Integer.parseInt(allrows.getString(cindex2)) ;
                                but.setId(ind);
                                butt.setId(ind);
                                nam.setId(ind);
                                but.setOnClickListener(new View.OnClickListener() {
                                                public void onClick(View v)
                                                {
                                                                f=1;
                                                                int i=but.getId();
                                                                SQLiteDatabase mydb;
                                                                mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
                                                                mydb.delete(TABLE,"_id="+i, null);
                                                                mydb.close();
                                                                Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
                                                                addTask();
                                                }
                                });


                                butt.setOnClickListener(new View.OnClickListener() {
                                                public void onClick(View v)
                                                {
                                                               butt.setText("Save");
                                                               nam.setText(tv.getText());
                                                               mail.setText(tv1.getText());
                                                               butt.setOnClickListener(new View.OnClickListener() {
                                                               public void onClick(View v)   {
                                                                             f=1;
                                                                             int j=but.getId();
                                                                             SQLiteDatabase mydb;
                                                                             mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
;
                                                                             ContentValues newrow1 = new ContentValues();
                                                                             String a=nam.getText().toString();
                                                                             String b=mail.getText().toString();
                                                                             if(a.trim().length()!=0&& b.trim().length()!=0)                                                                                {                                                                                                newrow1.put("name", nam.getText().toString());
                                                                                                  newrow1.put("email", mail.getText().toString());
                                                                                                  mydb.update(TABLE,newrow1, "_id="+j, null);
                                       
                                                                                                  Toast.makeText(getApplicationContext(), "Updated",
                                                                                                                            Toast.LENGTH_SHORT).show();
                                                                                                  nam.setText(null);
                                                                                                  mail.setText(null);
                                                                                                  butt.setText("Edit");
                                                                                                  addTask();
                                                                               }    else                                                                                {
                                                                                         //if(f==0)
                                                                                           Toast.makeText(getApplicationContext(), "Fields cannot be left blank",
                                                                                                                                 Toast.LENGTH_SHORT).show();
                                                                         }                                                                                mydb.close();
                                                                    }
                                                            });
                                                }
                                });
                                tv.setText(allrows.getString(cindex));
                                row.addView(tv);
                                tv1.setText(allrows.getString(cindex1));
                                row.addView(tv1);
                                row.addView(butt);
                                row.addView(but);
                                layout.addView(row);
                }while(allrows.moveToNext());
                }
                else
                {
                                layout.removeAllViews();
                                Toast.makeText(getApplicationContext(), "Table is empty", Toast.LENGTH_SHORT).show();
                }
                mydb.close();
    }
}

In the XML file set up a TableLayout with android:stretchColumns=”0,1″
and other buttons also and proceed.

Please leave your valuable comments.

How to dynamically add controls in Adobe AIR or Flex?

Below example shows how to add a label control dynamically in AIR or FLEX.

var L : Label = new Label();
L.addEventListener(MouseEvent.CLICK,LabelListener);
L.name = “my_label_name”;
L.text = “my Text”;
addChild(L);

// This function listens to the mouse click in the above added label.
private function LabelListener(event:MouseEvent):void
{
}

Please note that you can add any control by this method.
You can also add any controls inside a container like VBox by this method.
The above code works for only Flex SDK 3 for working in Flash builder or SDK 4 or above you need to change the above code like this.

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

How to remove unwanted frames from memory in iPhone?

In Cocos2D in iPhone often you may be using spritesheets which amy cause memory leaks because they are unused textures in memory even when you go from one scene to other. So make sure to remove all those unwanted textures from memory to save memory.

Copy this following code to dealloc function in your class which will remove all unwanted textures.

[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
[[CCTextureCache sharedTextureCache] removeUnusedTextures];

Please post your valuable comments on this post….

How to check whether your body is moving or it is in rest in box2D iPhone or ANDROID?

To check whether your body is in rest or not you need to check whether the body->IsAwake() function returns true.IF yes then your body is at rest. Take a look at the following snippet.

b2Body *body;
if(body->IsAwake())
{
       //Your body is awake, not in rest…
}
else {
       // Your body is in rest…..
}

Draw primitive shapes such as rectangle, circle etc in ANDROID, A simple example.

The following example shows how to draw a rectangle using the Paint Class in ANDROID. Just copy and paste the following code to your file and you are done.

package Draw2.pack;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class Draw2 extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(new myView(this));
  }

  private class myView extends View{

      public myView(Context context) {
          super(context);
      }

      @Override
      protected void onDraw(Canvas canvas) {

          Paint myPaint = new Paint();
          myPaint.setColor(Color.GREEN);
          myPaint.setStyle(Paint.Style.STROKE);
          myPaint.setStrokeWidth(3);
          canvas.drawRect(10, 10, 100, 100, myPaint);
      }
  }
}

Dynamically Load images in ANDROID? OR Load image in ANDROID using a string path.

With the following code you can load images in your drawable folder dynamically by giving the filename as a String. For that you have to use getResources().getIdentifier which has parameters as the “path”,”drawable” and the “package name”. This returns a unique resource ID which can be used to set the image for a ImageView using

imageView.setImageResource(imgID);

public void changeImage(String path)
{
    try
    {
          int imgID = getResources().getIdentifier(path, "drawable",
                        "your_package_name_here");
          imageView.setImageResource(imgID);
    }
    catch(Exception e)
    {
         Toast.makeText(MyActivity.this,e.getMessage() + "Error : ",
         Toast.LENGTH_SHORT).show();
    }
}

Play all songs from your raw directory in ANDROID continuously.

In ANDROID all resource has a unique resource ID which we get by passing the song name to the function below playSong().

The function getAllResourceIDs() will convert this String which is the name of the song to the unique resource ID which can then be used to play the song.

setOnCompletionListener() will be executed when the MediaPlayer completes playing a song with in which you can call this function again with next song parameter to play the next song.

public int songId = 0;
public void playSong(String to_play_song)
{
       songId = getAllResourceIDs(R.raw.class, to_play_song);
       mp = MediaPlayer.create(geetaact.this,songId);
       try
       {
               mp.prepare();
       }
       catch (IllegalStateException e) {
                  e.printStackTrace();
       } catch (Exception e) {
                 e.printStackTrace();
       }
       mp.start();

       //Called when the song completes.....
      mp.setOnCompletionListener(new OnCompletionListener()
      {
	      public void onCompletion(MediaPlayer mp)
	      {
	            //Get next song and play again continuosly.
	     }
	  );
}

//function which returns the unique resource ID.
public static int getAllResourceIDs(Class c, String song) throws IllegalArgumentException
{
           //System.out.println("inside HashMap"+ song);
       HashMap resmap = new HashMap();
       java.lang.reflect.Field[] fields = c.getFields();
       try
       {
               for(int i = 0; i < fields.length; i++)
               {
	               if(song != null)
	                     if(fields[i].getName().startsWith(song))
	                        resmap.put(fields[i].getName(), fields[i].getInt(null));
	                else
	                     resmap.put(fields[i].getName(), fields[i].getInt(null));
               }
       } catch (Exception e)
       {
                  throw new IllegalArgumentException();
       }
       Integer one = (Integer) resmap.get(song);
       int songid = one.intValue();
       return songid;
   }
}

HTTPClient in Titanium iPhone or ANDROID. How to check whether you request is complete?

function sendRequest()
{
	   var xhr = Titanium.Network.createHTTPClient();
	   xhr.onload = function()
	   {
		    if(this.status == 200)
		    {
		    	// this becomes true if your request is completed.
		    }
	   };
};
xhr.open('POST','http://your_domain.com/test.php');
xhr.send({ 'data':data});
xhr.onerror = function()
{
    Titanium.API.info('error');
    Titanium.UI.createAlertDialog({title:'Error ', message:'Please check your internet connection'}).show();
};

Trim() function in ActionScript(Adobe AIR , FLEX etc)…

The function for trim in ActionScript is defined inside StringUtil Class.
Checkout the following function.

public function stringTrim(result:String):String{

      result = StringUtil.trim(result);
trace(result);
return result;

}

Please post your valuable comments if the post was useful.

The function for trim in ActionScript is defined inside StringUtil Class.
Checkout the following function.

public function stringTrim(result:String):String{

      result = StringUtil.trim(result);
trace(result);
return result;

}

CCMenu Animation in Cocos2d iphone

You cal also animate CCMenu like other sprites to have some effect on your Menu.
You can also place spritesheets in each MenuItem.

-(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];
}

-(void) loadMenu
{
	CGPoint point1 = CGPointMake(570, 160);
	CGPoint point2 = CGPointMake(400,160);
	id FwdactionMove = [CCMoveTo actionWithDuration:.1 position:point1];
	id ReverseactionMove = [CCMoveTo actionWithDuration:.1 position:point2];
	id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(done1:)];
	[top_menu runAction:[CCSequence actions:FwdactionMove, ReverseactionMove,actionMoveDone, nil]];

}
-(void) menuGoBack
{

	[[CCDirector sharedDirector] resume];
	CGPoint point1 = CGPointMake(300, 160);
	CGPoint point2 = CGPointMake(570,160);
	id FwdactionMove = [CCMoveTo actionWithDuration:.1 position:point1];
	id ReverseactionMove = [CCMoveTo actionWithDuration:.1 position:point2];
	id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(goingBackMenu)];
	[top_menu runAction:[CCSequence actions:FwdactionMove, ReverseactionMove,actionMoveDone, nil]];
	[self backgroundGoBack];
}
-(void) done1:(id) sender
{
	[[CCDirector sharedDirector ] pause];
}

The above example moves the menu item from right to left and clicking on refresh it will go back.
The button that calls the loadMenu function will pause the screen and on refresh it will resume.

Access a remote database from Adobe AIR or FLEX.

Access a remote database from Adobe AIR or FLEX.

Many often you need to access online database from your application. For doing it in Adobe AIR of FLEX you need HttpService.
The following example shows how to access an online database from an AIR Application.
Note that you cannot return an array from a remote file or database, because the request is an asynchronous request. You can have a string as comma separated or some other separated which can be then send to our application. You can then split the string in your application according to your need.

Look at the example below which shows how to do this.

xmlns:mx="http://www.adobe.com/2006/mxml"
                  layout="absolute" applicationComplete="init()">
id="sender" url="http://localhost/testDB/index.php"
method="POST" resultFormat="text" result="resultHandler()" >
xmlns="">
                 { "ID"  }
import mx.utils.StringUtil;
import mx.rpc.events.FaultEvent;
import mx.controls.Alert;
public var result:String = "";

public function init():void{

      sender.addEventListener(FaultEvent.FAULT,errorOccurred);
      sender.send();          //sending request to php file.

}
public function errorOccurred(event:FaultEvent):void{
      trace('Invalid request');
      Alert.show('Invalid request');
}
public function resultHandler():void{

      result  = sender.lastResult.toString();  //get the result here from php as a string.
      trace(result);
      var arr : Array = new Array();

      arr = result.split("||",result.length);
      arr.pop();                                // remove the last blank element.....

      for(var i : int = 0; i < arr.length; i++){
            trace(arr[i]);
      }
}
]]>

The php part is given below

 $con = mysql_connect("localhost","root","");
if (!$con)
{
	die('Could not connect: ' . mysql_error());
}
mysql_select_db("testDB", $con);
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result))
{
      echo $row['user_id']."||";
}
mysql_close($con);

How to use the Particle Designer and export the file in your Xcode?

Follow these steps….

  1. Select your particle system from the Particle Designer .
  2. The go to file-> save as “file.plist”
  3. Copy file.plist to your resources folder.
  4. Copy the following code to your Xcode.
// in the .h file declare this.

CCParticleSystemQuad *emitter;
</pre>
Copy the code given below to the implementation file
<pre class="brush:c">
-(void) particleShow
{
    emitter.position = ccp(screenSize.width/2,screenSize.width/2);
    emitter = [CCParticleSystemQuad particleWithFile:@"file.plist"];
   // emitter.life =0.3;
   // emitter.duration = 0.50;
    [self addChild:emitter];
   // emitter.autoRemoveOnFinish = YES;
    [emitter release];
}

The RatingBar in ANDROID

Simply copy and paste the following code to see how to use the RatingBar in ANDROID.

package AndroidRatingBar.pack;

import android.app.Activity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.Toast;

public class AndroidRatingBar extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       final RatingBar ratingBar_Small = (RatingBar)findViewById(R.id.ratingbar_Small);
       final RatingBar ratingBar_Indicator = (RatingBar)findViewById(R.id.ratingbar_Indicator);
       final RatingBar ratingBar_default = (RatingBar)findViewById(R.id.ratingbar_default);

       ratingBar_default.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener(){

   @Override
   public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {

    ratingBar_Small.setRating(rating);
    ratingBar_Indicator.setRating(rating);
    Toast.makeText(AndroidRatingBar.this, "rating:"+String.valueOf(rating),
      Toast.LENGTH_LONG).show();
   }});
   }
}

Crop an Image in Adobe AIR or Flex.

Below code shows how to crop an image in Adobe AIR. Change the mx:WindowedApplication to mx: Application to run it as a FLEX Application.

The code uses copyPixels to extract the desired part from the image file.

The important line in the below code crops the image.
cropBD.copyPixels(loadBD, new Rectangle(startPoint.x, startPoint.y, squareSize, squareSize),posPoint);



    
        

    
    
    

    
    

    
    

    
    


Using StyleManager in Adobe AIR and FLEX.

StyleManager can be used to change the theme of any control in Adobe AIR and Flex.
The code shows how to sue StyleManager and dynamically change the theme of your window and others.




HBox{
 backgroundColor: #ffffff;
}


	

		

Dynamically change the background of a window in Adobe AIR?

Change the background of your window with your selected image.
Copy and paste the following code to your AIR file and view the result.

Note: Please make sure that you have an image in your application source folder.
Here the image name is “image.jpg” else you will get URL not found error.

xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"  creationComplete="onCreationComplete(event)" height="800" width="800" >



            import mx.events.FlexEvent;

            private var bgLoader : Loader;
            private var bgBitmapData : BitmapData;
// set your require background image path
            private var bgImagePath:String = "image.jpg";

/************************************************************************
backgroundImage="assets/myimage.jpg" height="800" width="800" >
</mx:WindowedApplication>
backgroundImage="assets/myimage.jpg" will set as a background Image.
************************************************************************/

            private function onCreationComplete(event:FlexEvent):void
            {
                bgLoader = new Loader ();
                bgLoader.contentLoaderInfo.addEventListener (Event.COMPLETE, bgLoadingComplete, false, 0, true);
  &nbs p;             bgLoader.load (new URLRequest (bgImagePath));
            }
            private function bgLoadingComplete (event:Event):void
            {
                bgBitmapData = new BitmapData (bgLoader.width, bgLoader.height);
                bgBitmapData.draw ( bgLoader );

                bgCanvas.graphics.beginBitmapFill (bgBitmapData);
                bgCanvas.graphics.drawRect (0, 0, stage.stageWidth, stage.stageHeight);
                bgCanvas.graphics.endFill ();
            }

        ]]>


    id="bgCanvas" height="100%" width="100%" />

Pass a variable from one window to another in Adobe AIR?

We often need to access another window variable in the current window.
The following example shows how to access a variable from one window in the next window.
The logic is to create an object of next window in the current window and assign the value of variable in the current window itself so that it becomes available in the net window.
Take a look at the example.

/*********** passVar.mxml *********************/

xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">


                  import mx.core.Window;

                  private function init():void
                  {
                        var myWindow : win = new win();
                        myWindow.myVar = "Hello";
                        myWindow.open();
                  }
            ]]>

      x="106" y="134" label="Button" click="init()"/>

/********************************************************************************
 win.mxml -> This file’s object is created in the first file. So please give the exact name, it’s case sensitive also.  Take a look at the line in passVar.mxml
              var myWindow : win = new win();
*********************************************************************************/

xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="400" height="300" creationComplete="init2()">


                  import mx.controls.Alert;

                  public var myVar : String = "";

                  private function init2():void
                  {
                        Alert.show(myVar,"Passed Variable",4,this);
                  }
            ]]>

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