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.

How to get the ANDROID SDK Version? How to get your Phone's IP Address in ANDROID? Also how to get your phone number from the phone?

Please checkout the “LogCat” for the output.
If you don’t know about Logcat In Eclipse “Go to Window->showView and search for Logcat”.

package com.ip;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

public class Get_IP extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
//        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        int ipAddress = wifiInfo.getIpAddress();
//        String ip = intToIp(ipAddress);

StringBuffer buf = new StringBuffer();
buf.append("VERSION.RELEASE {"+Build.VERSION.RELEASE+"}");
buf.append("nVERSION.INCREMENTAL {"+Build.VERSION.INCREMENTAL   +"}");
buf.append("nVERSION.SDK {"+Build.VERSION.SDK+"}");
buf.append("nBOARD {"+Build.BOARD+"}");
buf.append("nBRAND {"+Build.BRAND+"}");
buf.append("nDEVICE {"+Build.DEVICE+"}");
buf.append("nFINGERPRINT {"+Build.FINGERPRINT+"}");
buf.append("nHOST {"+Build.HOST+"}");
buf.append("nID {"+Build.ID+"}");
System.out.println("build"+buf);

System.out.println("Phone Number = " + getMy10DigitPhoneNumber());
}
public String intToIp(int i) {

  return ((i >> 24 ) & 0xFF ) + "." +
  ((i >> 16 ) & 0xFF) + "." +
  ((i >> 8 ) & 0xFF) + "." +
  ( i & 0xFF) ;
}
private String getMyPhoneNumber(){
 TelephonyManager mTelephonyMgr;
 mTelephonyMgr = (TelephonyManager)
 getSystemService(Context.TELEPHONY_SERVICE);
 return mTelephonyMgr.getLine1Number();
 }

 private String getMy10DigitPhoneNumber(){
 String s = getMyPhoneNumber();
 return s.substring(2);
 }
}

How to use Webview in ANDROID together with javascript?

The following java code helps you to show a webpage in ANDROID and enable javascript.

package com.pack;

import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.SumPathEffect;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnKeyListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

public class myHTML extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

     getWindow().requestFeature(Window.FEATURE_PROGRESS);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        WebView webview = (WebView)findViewById(R.id.webview);
        TextView tv = (TextView)findViewById(R.id.tv);

        tv.setOnKeyListener(new OnKeyListener() {
 @Override
 public boolean onKey(View v, int keyCode, KeyEvent event) {

 return false;
 }
 });

        try{

             webview.getSettings().setJavaScriptEnabled(true);
        //  setContentView(webview);

              final Activity activity = this;
              webview.setWebChromeClient(new WebChromeClient() {
           public void onProgressChanged(WebView view, int progress) {
             activity.setProgress(progress * 10000);
             Toast.makeText(activity, "Loading " , Toast.LENGTH_SHORT).show();
           }
         });

              webview.setWebViewClient(new WebViewClient() {
              public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
              Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
              }
         });

         String summary = "HELLO";

         /*To load from a string use loadDataWithBaseURL  */
         webview.loadDataWithBaseURL("",summary, "text/html", "utf-8", "");

         /* To load from a file use loadUrl(remote or local) */
         //webview.loadUrl("file:///android_asset/test.html");

        }catch(Exception e){
         Toast.makeText(myHTML.this,e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }
}

How to access a remote php file from ANDROID?

For working on the localhost use 10.0.2.2 and for remote use the IP or domain name of the server.
The following code does this.

package com.pack;

import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class active extends Activity
{
    HttpPost httpPost;
    ResponseHandler response;
    String result;
    HttpClient htClient;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Toast.makeText(active.this,"Accessing.....", Toast.LENGTH_SHORT).show();

        htClient = new DefaultHttpClient();
        httpPost = new HttpPost("http://10.0.2.2/DB_TEST/android_test.php");
 response = new BasicResponseHandler();
 try
 {
 result = htClient.execute(httpPost,response);
 Toast.makeText(active.this,result, Toast.LENGTH_SHORT).show();
 }
 catch (ClientProtocolException e) {

 Toast.makeText(active.this,e.getMessage(), Toast.LENGTH_SHORT).show();
 }
 catch (IOException e) {
 Toast.makeText(active.this,"IO Error " + e.getMessage(), Toast.LENGTH_LONG).show();
 }
    }
}

Detect when the ANDROID Screen Goes Off ?

This is the main Java file that extends activity.
Create a file named ScreenON_OFF_ACTIVITY.java and place the below code in it.

package com.pack;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class ScreenON_OFF_ACTIVITY extends Activity {

  public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         onCreate();
  }
  public void onCreate() {

         // initialize receiver
     System.out.println("onCreate1 ");
         IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
         filter.addAction(Intent.ACTION_SCREEN_OFF);
         BroadcastReceiver mReceiver = new ScreenReceiver();
         registerReceiver(mReceiver, filter);
         System.out.println("onCreate ");
     }

     @Override
     protected void onPause() {
         // when the screen is about to turn off
         if (ScreenReceiver.screenOff) {
             // this is the case when onPause() is called by the system due to a screen state change
             System.out.println("SCREEN TURNED OFF");
         } else {
             // this is when onPause() is called when the screen state has not changed
           System.out.println("this is when onPause() is called when the screen state has not changed ");

         }
         super.onPause();
     }
     @Override
     protected void onResume() {
         // only when screen turns on
         if (!ScreenReceiver.screenOff) {
             // this is when onResume() is called due to a screen state change
             System.out.println("SCREEN TURNED ON");
         } else {
             // this is when onResume() is called when the screen state has not changed
           System.out.println(" this is when onResume() is called when the screen state has not changed ");
         }
         super.onResume();
     }
 }

This is the class that extends the Broadcast receiver class that receives the notifications.
create a java file and name it ScreenReceiver.java and place the following code in it.

package com.pack;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class ScreenReceiver extends BroadcastReceiver {

    public static boolean screenOff;

    @Override
    public void onReceive(Context context, Intent intent) {

      System.out.println("onReceive ");
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            screenOff = true;
            System.out.println("SCREEN TURNED OFF on BroadcastReceiver");
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            screenOff = false;
            System.out.println("SCREEN TURNED ON on BroadcastReceiver");
        }
        Intent i = new Intent(context, UpdateService.class);
        i.putExtra("screen_state", screenOff);
        context.startService(i);
    }

}

This the class that updates the service name it UpdateService.java.

package com.pack;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

public class UpdateService extends Service {

    public void onCreate() {
        super.onCreate();
        // register receiver that handles screen on and screen off logic

        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        boolean screenOn = intent.getBooleanExtra("screen_state", false);
        if (!screenOn) {
         System.out.println("Screen is off");
        } else {
            System.out.println("Screen is on");
        }
    }

 @Override
 public IBinder onBind(Intent intent) {
 return null;
 }
}

How will you access the clipboard in an AIR application?

The following is a sample code to do this.
Simply copy and paste.

<xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">

            public function init():void{
                  var str : String = "Hello";
                  System.setClipboard(str);

                  var versionString:String = Capabilities.version;
                  var pattern:RegExp = /^(w*) (d*),(d*),(d*),(d*)$/;
                  var result:Object = pattern.exec(versionString);
                  if (result != null)
                  {
                        trace("input: " + result.input);
                        trace("platform: " + result[1]);
                        trace("majorVersion: " + result[2]);
                        trace("minorVersion: " + result[3]);
                        trace("buildNumber: " + result[4]);
                        trace("internalBuildNumber: " + result[5]);
                        trace("MP3 playBack : " + Capabilities.hasMP3);
                        trace("Res  X "+ Capabilities.screenResolutionX);
                        trace("Res  Y "+ Capabilities.screenResolutionY);
                        trace(" IME Installed " + Capabilities.hasIME);

                        if (Capabilities.hasIME)
                        {
                              if (IME.enabled)
                              {
                              trace("IME is installed and enabled.");
                              }
                              else
                              {
                              trace("IME is installed but not enabled. Please enable your IME and try again.");
                              }
                        }
                        else
                        {
                              trace("IME is not installed. Please install an IME and try again.");
                        }
                  }
                  else
                  {
                        trace("Unable to match RegExp.");
                  }
                  if (Capabilities.hasIME)
                  {
                        switch (IME.conversionMode)
                        {
                        case IMEConversionMode.ALPHANUMERIC_FULL:
                        trace("Current conversion mode is alphanumeric (full-width).");
                        break;

                        case IMEConversionMode.ALPHANUMERIC_HALF:
                        trace("Current conversion mode is alphanumeric (half-width).");
                        break;
                        case IMEConversionMode.CHINESE:
                        trace( "Current conversion mode is Chinese.");
                        break;
                        case IMEConversionMode.JAPANESE_HIRAGANA:
                        trace( "Current conversion mode is Japananese Hiragana.");
                        break;
                        case IMEConversionMode.JAPANESE_KATAKANA_FULL:
                        trace( "Current conversion mode is Japanese Katakana (full-width).");
                        break;
                        case IMEConversionMode.JAPANESE_KATAKANA_HALF:
                        trace( "Current conversion mode is Japanese Katakana (half-width).");
                        break;
                        case IMEConversionMode.KOREAN:
                        trace( "Current conversion mode is Korean.");
                        break;
                        default:
                        trace("Current conversion mode is " + IME.conversionMode + ".");
                        break;
                        }
                  }
                  else
                  {
                        trace("Please install an IME and try again.");
                  }
            }
      ]]>

How to read and write an XML file in Adobe AIR or Flex?

AIR treats the XML files as just as normal file and so you can proceed using the FileStream classs. Please take a look at the sample code. Just copy and paste the following code to your main.MXML file and you are done.

  import flash.xml.XMLDocument;

  private function init():void
  {
   xmlTA.text = " Sample XML ";
   var fileStream:FileStream = new FileStream();
   var prefsXML:XML =
           Sample
           XML
        ;

   var file:File = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream = new FileStream();
   fileStream.open(file, FileMode.WRITE);

   var outputString:String = 'n';
   outputString += prefsXML.toXMLString();

   fileStream.writeUTFBytes(outputString);
   fileStream.close();

   /* Reading the XML File */
   file = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream.open(file, FileMode.READ);
   prefsXML= XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
   readTA.text = prefsXML;
   fileStream.close();

   /*
    The previous examples use FileStream objects opened for synchronous operation.
    You can also open files for asynchronous operations (which rely on event listener functions to respond to events).
    For example, the following code shows how to read an XML file asynchronously:
   */

   file = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream = new FileStream();
   fileStream.addEventListener(Event.COMPLETE, processXMLData);
   fileStream.openAsync(file, FileMode.READ);

   function processXMLData(event:Event):void
   {
       prefsXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
       asyXML.text = prefsXML;
       fileStream.close();
   }

  }
 ]]>

Please post your comments on this post

Add Context menu in Adobe AIR or FLEX.

This sample shows how to add a menu to your context menu or the right click of your menu in Adobe AIR. AIR Uses the ContextMenu class to add menu to your mouse right click.

  import flash.events.ContextMenuEvent;
   import mx.controls.Alert;
   // call this function to create context menu in AIR and FLex
   private function createContextMenu():void
   {
      var myContextMenu:ContextMenu = new ContextMenu();
     this.contextMenu = myContextMenu;       //add menu items

     var myMenuItem1:ContextMenuItem = new ContextMenuItem('Menu Item 1');
     var myMenuItem2:ContextMenuItem = new ContextMenuItem('Menu Item 2');

     myContextMenu.customItems = [myMenuItem1, myMenuItem2 ];

     //add event listeners to menu items
     myMenuItem1.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemClick1);
     myMenuItem2.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemClick2);

    }     // listener functions for context menu items
       private function menuItemClick1(event:Event):void
       {
        //Write here the code for on click of item 1
        Alert.show('Menu Item 1 clicked');
       }
       private function menuItemClick2(event:Event):void{
           //Write here the code for on click of item 2
           Alert.show('Menu Item 2 clicked');
   }
 ]]>