Test driving Push notification in Bluemix

This post is a continuation of my earlier post ‘Getting started with mobile cloud in Bluemix‘. Here I take a test drive of the push service that Bluemix offers based on the article “Extend an Android app using the Push cloud service” from developerWorks.

This post assumes that you have already completed the changes from my earlier post for the mobile cloud. If you haven’t,  you could clone the code from “mobile data” which is the official IBM version of this app and includes all the changes needed for persisting data in the cloud through their Android.

The Mobile Cloud App I created on Bluemix is “mobtvg“. The main steps to have Push notification service using Bluemix are

  1. GCM services : Get Google API Project number  & GCM API Key
  2. Include the Google Play services library project
  3. Add the jar files to enable Push service
  4. Modify the server side Node.js file to send push notifications to all registered devices
  5. Make necessary code changes
  6. Run the application and test for notification

Here are more details on the above steps

a) GCM services : Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users’ Android-powered device, and also to receive messages from devices on the same connection. The 1st thing to do is get the Google API Project number & GCM API key.

– Click on Google Developer Console

– Click Create Project. Enter Project name & click Create.

– Note the Project Number on top of the page.

– Click API & Auth on left panel. Click API.

– Scroll down and turn-on Google Messaging for Android

–  Click credentials and click “Create new key”. Click server key. Click create

-Copy API key in the Public API access

Now go the Bluemix dashboard and click your application. Click the Push module. In the Configuration tab, scroll down to Google Cloud Messaging and  click ‘Edit’

Enter the Google API Project Number & GCM API key for both the Sandbox & Production configuration and click Save.

4
b) In Eclipse click Windows->Android SDK manager. Scroll down to the bottom and under Extras select Google Play services. Click install. Once the installation is successful import the project as follows File-Import->Android->Existing Android  code into Workspace. Click Next. In the next screen Browse to the path where your ADT bundle is installed and choose the folder

<ADT-Bundle>\ sdk\extras\google\google_play_services

and Click Ok. Also  check ‘Copy project into workspace’. This will copy.

3

Now build the Google Play Services Project. To do this the project. Click Project->Properties->Android and make sure that you select ‘Is library project’ and then click build.

5

Add a reference to the Google Play services in the Androidmanifest.xml

<meta-data

android:name=”com.google.android.gms.version”

android:value=”@integer/google_play_services_version” />

c) Make all the code changes given in Step 4 of “Extend an Android app using the Push cloud service.

d) In MainActivity.java make sure you change the app_name to the name of your app for e.g

public static final String CLASS_NAME = “MainActivity”;

public static final String APP_NAME = “mobtvg“;

Also ensure that under assets folder you have populated the Application ID in the bluemix.properties file

applicationID=<Application ID from Bluemix>

d) Add ibmcloudcode.jar, ibmpush.jar, android-support-v4.jar (from <Android_SDK_Location>/extras/android/support/v4)

e) Now the Mobile Push project need to include this library project. To do this select your Mobile App project. Click Project->Properties->Android. Click Add and select google-play-services-lib. Note: Make sure “Is library project” is unchecked otherwise you are in for a lot of grief.

8

f) Now you need to make changes to the Node.js application to push any changes from the server to all registered devices.  The code for this is in bluelist-push-node. Note; Making changes through the GUI results in an error that “manifest.yml is not in root node”. So I suggest that you take the ‘cf’ route as follows.

– Clone the code using Git

git clone https://hub.jazz.net/git/mobilecloud/bluelist-push

Go to bluelist-push-node folder

i) Open the app.js with your favorite editor and enter the Application ID of your Bluemix application

//Data Values

var values = {

version:”0.3.1″,

//change this to the actual application id of your mobile backend starter

appID : “<APPLICATION ID>”,

host : “https://mobile.ng.bluemix.net&#8221;

}

ii) Open manifest.yml and change host name & name to the name of your application for e.g.

host: mobtvg

disk: 1024M

name: mobtvg

command: node app.js

path: .

domain: ng.bluemix.net

mem: 128M

instances: 1

iii) Once the changes are complete, open a command propmpt and  login into Bluemix using ‘cf’ as follows

– cd to the directory in which Node.js & manifest.yml exist, Do

cf login – a http://api.ng.bluemix.net

cf push mobtvg -p . -m 512M

(Note the changes are pushed to the mobile cloud app on Bluemix)

This will run through and finally give the status that the app is running successfully.

f) Now that all changes are complete the Mobile Cloud with Push can be tested..

g) Click Window->Android Virtual Device Manager. Click the Device definitions. You choose Google Nexus, Nexus 7. Click Create AVD.

Note: Make sure you choose Google API Level Y and not Android x.x.x API Y.

6

Let the AVD come up and display the current items in the grocery list.

h) Login to Bluemix. Click Push and select the Notifications tab and enter a test message for e.g. “This is a notification from Bluemix” and click send.

7

This will result in a Push Notification to be sent to the AVD. You should see this popup on you AVD as shown below

1

i) Add another AVD through Windows-Android Virtual Device manager. While one AVD is running go to Run->Run Configurations->Target Device and choose the newly created AVD.

j) This will start a second AVD which will refresh with the contents of the grocery list. Now adda new item in one of AVD devices. This will result in a Push notification to the other device that the Bluelist has been updated.

2

There you have it.

1) A mobile cloud applications in which changes persist in the cloud and are refreshed each time the Android device is restarted.

2) A Push notification that is sent to all registered devices whenever there is a change to the list.

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

Find me on Google+

Getting started with a Mobile Cloud app with Bluemix

This post gives the key steps to get going in building a Mobile Cloud application on IBM’s Bluemix. This post focuses on using the Android Platform for building the application. IBM Bluemix’es mobile cloud application includes under its hood mobile services like mobile application security, push and mobile data. A Node.js is also thrown in to provide server-side functions.

The Bluemix Mobile architecture is shown below

BuildingMobile

 

As in the previous post an existing Mobile cloud application IBM’s bluelist -base is cloned to get familiarity with the steps involved. The IBM’s bluelist-base app enables the user to maintain a grocery list that persists as mobile data in the cloud instance. To get started perform the following

1) Install ADT + Eclipse bundle from the aforementioned link

2) Unzip and install Eclipse and the ADT bundle

3) Make sure you have the Java JDK for Eclipse. If not install from the following site Java SE Development Kit 8 Downloads

4) Since we will be cloning an existing application and using Eclipse to make the changes we need to install EGit.

5) To do this open Eclipse and select Help-> Install New Software and type in http://download.eclipse.org/egit/updates in the Work with text field and hit enter. You should see the following

1

6) Once EGit is installed the IBM’s bluelist-base App can be cloned as follows

7) In Eclipse click File->Import->Git->Import from Git and click Next

8) Choose Clone URI and Click Next

9) Enter the URI for IBM’s bluelist-base. This shown below

2

10) This will download all the necessary source files and other Android related files and directories into the workspace.

11) After this perform the Steps 2 to Step 6 from the link given Build an Android app using the MobileData cloud service

12) After you make the necessary code changes you are good to go

13) Make sure you right-click and add all the necessary imports required (also Ctrl+Shift + O)

14) Build the Project and make sure that there are no errors

15) You are now ready to run the mobile cloud application. We need to run the mobile app on a Virtual simulator. This can be done as

a) In Eclipse click Window->Android Virtual Device Manager. Click the Device Definitions tab.

b) Choose Nexus 7 (Google) and Click Create AVD.
c) This will open a New Window. Set the following Skin->QVGA and Enter 100 MiB in SD Card size and click OK. This will add this as a AVD.

16) Now run the application.

17) This will bring up the AVD. This takes some time You should see the IBM bluelist showing up as one of the apps.

18) Click on IBM Bluelist. You can add grocery items. These items will persist even if you have to restart your application

3

19) The data is persisted in the IBM’s cloud. This can be checked by logging into BlueMix’es dashboard

4

20) Click the Mobile Data and the data entered in the AVD device will show up in Data Classes drop down.

5

21) The Analytics tab will give a graphical output of the API calls

6

So not the mobile app that is cloud enabled is ready.

Clearly the ability to build Android Apps with the data stored at a cloud opens up numerous possibilities for apps like Evernote, Pocket across several devices.

There you have your first Mobile Cloud App.

Watch this space!

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

Find me on Google+

A closer look at “Robot Horse on a Trot” in Android

DSC00078This post is result of my dissatisfaction with the awkward and contrived gait of my Robot Walker in my earlier post “Simulating a Robot Walker” in Android. The movements seemed to be a little too contrived for my comfort so I decided to make a robot which has far more natural movements.

You can see the clip at Robot Horse on a canter using Android on Youtube
The complete code can be cloned at GitHub RobotHorse

To do this I pondered on what constitutes a walking motion for any living thing. With a little effort it is clear that the following movements occur during walking

Mechanics of leg movements during walking

  1. The upper part of the leg swings upward and downward pivoted at the hip.
  2. The lower part of the leg, pivoted at the knee, swings in the opposite direction to the upper part of the leg. i.e when the upper part swings upward and counter-clockwise, the lower part of the leg swings downward & clockwise which results in the bend at the knees
  3. When one leg goes up, counterclockwise, the other leg goes down or it swing clockwise and vice versa. See figure below

horse

So with these rules it was easy to make the legs.

Frontal leg (first leg)
The upper part of the leg is connected to the Robot Body through a revoluteJoint with a pivot at the body. The upper leg has a motor and swings between an upper and lower limit
// Create upper leg
upperLeg = new Sprite(x, y, this.mLegTextureRegion, this.getVertexBufferObjectManager());
upperLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, upperLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(upperLeg, upperLegBody, true, true));
this.mScene.attachChild(upperLeg);

//Create an anchor/pivot at the body of the robot
Vector2 anchor1 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT,y/PIXEL_TO_METER_RATIO_DEFAULT);
//Attach upper leg to the body using a revolute joint with a motor
final RevoluteJointDef rJointDef = new RevoluteJointDef();
rJointDef.initialize(upperLegBody, robotBody, anchor1);
rJointDef.enableMotor = true;
rJointDef.enableLimit = true;
rJoint = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef);
rJoint.setMotorSpeed(4);
rJoint.setMaxMotorTorque(15);

//Set upper and lower limits for the swing of the leg
rJoint.setLimits((float)(0 * (Math.PI)/180), (float)(30 * (Math.PI)/180));

//Fire a periodic timer
new IntervalTimer(secs,rJoint);

The lower leg pivoted to the bottom of the upper leg through a revoluteJoint swings in the opposite direction of the upper leg between the reverse angle limts. By the way, I had tried every possible joint between the lower & the upper leg (distanceJoint, weldJoint,prismaticJoint) but the revoluteJoint is clearly the best.

// Create lower leg
lowerLeg= new Sprite(x, (y+50), this.mLegTextureRegion, this.getVertexBufferObjectManager());
lowerLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, lowerLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(lowerLeg, lowerLegBody, true, true));
this.mScene.attachChild(lowerLeg);
Vector2 anchor2 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT, (y+50)/PIXEL_TO_METER_RATIO_DEFAULT);

//Create a revoluteJoint between upper & lower leg
final RevoluteJointDef rJointDef1 = new RevoluteJointDef();
rJointDef1.initialize(lowerLegBody, upperLegBody, anchor2);

// The lower leg swings in opposite direction to upper leg
rJointDef1.enableMotor = true;
rJointDef1.enableLimit = true;
rJoint1 = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef1);
rJoint1.setMotorSpeed(-4);
rJoint.setMaxMotorTorque(15);

//Set upper and lower limits for the swing of the leg
// Set appropriate limits for lower leg
rJoint1.setLimits((float)(-30 * (Math.PI)/180), (float)(0 * (Math.PI)/180));
new IntervalTimer(secs,rJoint1);
Rear Leg (alternate leg)

Every alternate leg moves in the converse direction as the previous leg

//Create the alternative leg
publicvoid createAltLeg(float x, float y, int secs ){
// Create upper part of leg
upperLeg = new Sprite(x, y, this.mLegTextureRegion, this.getVertexBufferObjectManager());
upperLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, upperLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(upperLeg, upperLegBody, true, true));
this.mScene.attachChild(upperLeg);
//Create an anchor/pivot at the body of the robot
Vector2 anchor1 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT,y/PIXEL_TO_METER_RATIO_DEFAULT);
//Attach upper leg to the body using a revolute joint with a motor
final RevoluteJointDef rJointDef = new RevoluteJointDef();
rJointDef.initialize(upperLegBody, robotBody, anchor1);
rJointDef.enableMotor = true;
rJointDef.enableLimit = true;
rJoint = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef);
// This leg swings in the opposite direction of the previous leg
rJoint.setMotorSpeed(-4);
rJoint.setMaxMotorTorque(15);
//Set upper and lower limits for the swing of the leg
rJoint.setLimits((float)(0 * (Math.PI)/180), (float)(30 * (Math.PI)/180));
new IntervalTimer(secs,rJoint);
// Create lower leg
lowerLeg= new Sprite(x, (y+50), this.mLegTextureRegion, this.getVertexBufferObjectManager());
lowerLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, lowerLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(lowerLeg, lowerLegBody, true, true));
this.mScene.attachChild(lowerLeg);
Vector2 anchor2 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT, (y+50)/PIXEL_TO_METER_RATIO_DEFAULT);
//Create a revoluteJoint between upper & lower leg
final RevoluteJointDef rJointDef1 = new RevoluteJointDef();
rJointDef1.initialize(lowerLegBody, upperLegBody, anchor2);
rJointDef1.enableMotor = true;
rJointDef1.enableLimit = true;
rJoint1 = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef1);
//The lower part of the leg has the opposite swing to the upper part
rJoint1.setMotorSpeed(4);
rJoint.setMaxMotorTorque(15);
//Set appropriate upper and lower limits for the swing of the leg
rJoint1.setLimits((float)(-30 * (Math.PI)/180), (float)(0 * (Math.PI)/180));
// Fire a periodic timer
new IntervalTimer(secs,rJoint1);
I attached a horse’s head to the body using a WeldJoint
//Create the horse and attach the head using a Weld Joint
horse = new Sprite(140, 320, this.mHorseTextureRegion, this.getVertexBufferObjectManager());
horseBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, horse, BodyType.DynamicBody, HORSE_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(horse, horseBody, true, true));
this.mScene.attachChild(horse);
Vector2 anchor = new Vector2(140/PIXEL_TO_METER_RATIO_DEFAULT, 320/PIXEL_TO_METER_RATIO_DEFAULT);
final WeldJointDef weldJointDef = new WeldJointDef();
weldJointDef.initialize(horseBody, robotBody, anchor);
this.mPhysicsWorld.createJoint(weldJointDef);

So now I had a horse that was ready to trot or canter around.

You can see the clip at Robot Horse on a canter using Android
The complete code can be cloned at GitHub RobotHorse

Some issues

Here are some issues with the above code

  • The horse is quite unstable. If I move the phone vertically, the horse tends to tip backwards. The above clip was recorded with the phone lying on a table
  • The motor speeds, torque and the masses of the different objects have to be adjusted very carefully. If the horse’s head or the body is too heavy the legs buckle under the weight
  • Sometimes when I start the simulation the horse seems to bounce off the floor

I have carefully adjusted the mass, friction, motor speeds etc very carefully. Feel free to play around with them.

Comments & suggestions are welcome.

Find me on Google+

“Is it an animal? Is it an insect?” in Android

walker“Is it an animal? Is it an insect?”. The answer is neither. In fact it is my version of a ‘robot walker’ in android using Box2D & AndEngine. I got interested in this simulation after I saw the Theo Jansen walker in JBox2D (look under Joints) . I did take a look at the code for this but I found it difficult to follow so I made my own version of a robot walker.

With the above the robot walker is able to walk awkwardly as seen in the video clip on Youtube – Robot Walker in Android
The entire project can be cloned at GitHub at RobotWalker

In this connection I would like to point yot to an excellent and a fascinating TED talk by the creator Theo Jansen himself on “My creations, a new form of life”. His creations are really jaw- dropping.

Anyway getting back to my post I thought about what would make the insect walk? After some thought I realized that I had to create a swinging motion of the upper part of the leg combined with the lower leg motion which does not bend that much.

So I created a robot body which is a flat rectangular shape

Create the robot body
robot = new Sprite(100, 360, this.mRobotTextureRegion, this.getVertexBufferObjectManager());
robotBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, robot, BodyType.DynamicBody, BODY_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(robot, robotBody, true, true));
this.mScene.attachChild(robot);
Creating legs
Then I create 6 different legs spaced apart
createLeg(100,360,1);
createLeg(120,360,1);
createLeg(140,360,1);
createLeg(160,360,1);
createLeg(180,360,1);
createLeg(200,360,1);
createLeg(220,360,1);
createLeg(240,360,1);
The createLeg() creates an upper and lower part of the leg. The upper part of the leg is connected to the body of the robot through a revoluteJoint as follows

Upper Leg
// Create upper leg
upperLeg = new Sprite(x, y, this.mLegTextureRegion, this.getVertexBufferObjectManager());
upperLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, upperLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(upperLeg, upperLegBody, true, true));
this.mScene.attachChild(upperLeg);
//Create an anchor/pivot at the body of the robot
Vector2 anchor1 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT,y/PIXEL_TO_METER_RATIO_DEFAULT);

//Attach upper leg to the body using a revolute joint with a motor
final RevoluteJointDef rJointDef = new RevoluteJointDef();
rJointDef.initialize(upperLegBody, robotBody, anchor1);
rJointDef.enableMotor = true;
rJointDef.enableLimit = true;
rJoint = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef);

Lower Leg
The lower leg is connected to upper leg through a distance joint
// Create lower leg
lowerLeg= new Sprite(x, (y+50), this.mLegTextureRegion, this.getVertexBufferObjectManager());
lowerLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, lowerLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(lowerLeg, lowerLegBody, true, true));
this.mScene.attachChild(lowerLeg);

// Connect the lower and upper leg with distance joint
Vector2 anchor2 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT, (y+50)/PIXEL_TO_METER_RATIO_DEFAULT);
//Create a distanceJoint between upper & lower leg
DistanceJointDef distanceJoint1 = new DistanceJointDef();
distanceJoint1.initialize(upperLegBody,lowerLegBody, anchor2,anchor2);
distanceJoint1.collideConnected = true;
distanceJoint1.dampingRatio = 0.5f;
distanceJoint1.frequencyHz = 10.0f;
this.mPhysicsWorld.createJoint(distanceJoint1);

 mqdefault

Creating a walking movement
To create a walking movement I create a timer task which triggers after a delay of 1 second periodically and makes the upper legs’s revoluteJoint swing between angles within an upper and lower limit.

new IntervalTimer(secs,rJoint);
The timer itself reverses the motor every time it fires
class RemindTask extends TimerTask {
RevoluteJoint rj1;;
RemindTask(RevoluteJoint rj){
rj1 = rj;
}
@Override
publicvoid run() {
reverseMotor();
}

publicvoid reverseMotor(){
rj1.setMotorSpeed(-(rj1.getMotorSpeed()));
rj1.setMaxMotorTorque(10);
}
}
With the above the robot walker is able to walk awkwardly as seen in the video Robot Walker in Android

The entire project can be cloned at GitHub at RobotWalker

I will probably be refining this sometime in the future. One good idea is to create a delay between the swings of different legs. Any thoughts suggestions on making the movement more fluid are more than welcome.

Take a look at some cool simulations using AndEngine & Box2D
1. Simulating the domino effect using Box2D and AndEngine
2. Bull in a china shop – Behind the scenes in android
3. Creating a blob in Android using  Box2D physics Engine & AndEngine
4. Blob with an attitude(stiffness) in Android
and a few more
Find me on Google+

Simulating an oscillating revoluteJoint in Android

DSC00074In this post I simulate an oscillating revoluteJoint in Android using Box2D physics engine & AndEngine. While I was attempting this in the context of something larger I found this fairly challenging so I decided to write a separate post on this.  Creating a revoluteJoint was rather trivial.  This was done as follows

Initially I created a static point to act as pivot.  I then used a rectangular shape joined at the pivot. I wanted this to oscillate about the pivot. So the pivot & the rectangular shape were created as follows
circle = new Sprite(100, 320, this.mBallTextureRegion, this.getVertexBufferObjectManager());

circleBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, circle, BodyType.StaticBody, FIXTURE_DEF);

this.mScene.attachChild(circle);

// Create leg

leg = new Sprite(110, 325, this.mLegTextureRegion, this.getVertexBufferObjectManager());

legBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, leg, BodyType.DynamicBody, gameFixtureDef);

this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(leg, legBody, true, true));

this.mScene.attachChild(leg);

Then I created a revoluteJoint between the leg and the circleBody as follows

final RevoluteJointDef rJointDef = new RevoluteJointDef();

rJointDef.initialize(legBody, circleBody, circleBody.getWorldCenter());

rJointDef.enableMotor = true;

rJointDef.enableLimit = true;

rJoint = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef);

rJoint.setMotorSpeed(2);

rJoint.setMaxMotorTorque(100);

rJoint.setLimits((float)(30 * (Math.PI)/180), (float)(270 * (Math.PI)/180));

The revoluteJoint has a lower limit of 30 degrees and an upper limit of 270 degrees.

To make it oscillate I created a Timer task which I fire every second. Every time the timer fires I reverse the motor speed as follows

class IntervalTimer {

Timer timer;

public IntervalTimer(int seconds, RevoluteJoint rj) {

Log.d(“Inside”,“in”);

timer = new Timer(); //At this line a new Thread will be created

timer.scheduleAtFixedRate(new RemindTask(rj), seconds*1000, 1000);

}

class RemindTask extends TimerTask {

RevoluteJoint rj1;;

RemindTask(RevoluteJoint rj){

rj1 = rj;

}

@Override

publicvoid run() {

Log.d(“x”,“x” +“Reversing motor”);

reverseMotor();

}

publicvoid reverseMotor(){

rj1.setMotorSpeed(-(rj1.getMotorSpeed()));

rj1.setMaxMotorTorque(100);

Log.d(“aa”,“speed:”+rj1.getMotorSpeed() + “torque:” + rj1.getMotorTorque());

}

}

}

I then instantiate the timer

new IntervalTimer(5,rJoint);

I now have an oscillating revoluteJoint which can be used in any number of ways.

The video clip is at “Simulating an oscillating revoluteJoint in Android

You can clone the project from GitHub at “oscillatingRevoluteJoint

Find me on Google+

Fun simulation of a Chain in Android

DSC00071In this post I simulate a Chain in Android using AndEngine & Box2D physics. Simulating a Chain is fairly straightforward. Initially I create a static point as an anchor point to suspend the Chain from

You can see the video at Fun simulation of a Chain in Android – I on Youtube

The project can be cloned from GitHib at Chain

 

link[0] = new Sprite((float) 360, (float) 20, this.mLinkTextureRegion, this.getVertexBufferObjectManager());

linkBody[0] = PhysicsFactory.createBoxBody(this.mPhysicsWorld, link[0], BodyType.DynamicBody, FIXTURE_DEF);

this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(link[0], linkBody[0], true, true));

this.mScene.attachChild(link[0]);

Then I create succeeding links to the initial link with revolute joints between them as follows

// Add links to chain with revolute joint between each link

for(int i =1; i < nBodies ; i++){

x[i] = x[i-1] + 8 * Math.cos(PI/4);

y[i] = y[i-1] + 8 * Math.sin(PI/4);

link[i] = new Sprite((float) x[i], (float) y[i], this.mLinkTextureRegion, this.getVertexBufferObjectManager());

linkBody[i] = PhysicsFactory.createBoxBody(this.mPhysicsWorld, link[i], BodyType.DynamicBody, FIXTURE_DEF);

this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(link[i], linkBody[i], true, true));

this.mScene.attachChild(link[i]);

revoluteJointDef = new RevoluteJointDef();

revoluteJointDef.initialize(linkBody[i], linkBody[i-1], linkBody[i-1].getWorldCenter());

revoluteJointDef.enableMotor = false;

revoluteJointDef.motorSpeed = 0;

revoluteJointDef.maxMotorTorque = 0;

this.mPhysicsWorld.createJoint(revoluteJointDef);

Finally I suspend a monkey as the last body to the Chain.

I have added plated for the 2 walls (right & left) and also the floor as collisions can be detected between bodies.

@Override

protectedvoid onManagedUpdate(finalfloat pSecondsElapsed) {

// Check collisions

if(rWall.collidesWith(this) ){

x = this.getX();

y = this.getY();

bText.setPosition(x-40,y – 20);

bText.setText(“Bonk!”);

}

if(lWall.collidesWith(this)){

x = this.getX();

y = this.getY();

bText.setPosition(x + 20,y – 20);

bText.setText(“Thump!”);

}

if(floor.collidesWith(this)){

x = this.getX();

y = this.getY();

bText.setPosition(x – 20,y – 20);

bText.setText(“Thud!”);

}

With all these under gravity we have a nice Chain effect!

You see the video at Fun simulation of a Chain in Android – I

The project can be cloned from GitHib at Chain

Take a look at some cool simulations using AndEngine & Box2D
1. The making of Total Control Android game
2. Simulating an Edge Shape in Android
3. Simulating a Web Joint in Android
4. Modeling a Car in Android
5. A closer look at “Robot horse on a Trot! in Android”
and a couple more
Find me on Google+

Modeling a Car in Android

DSC00065

In this post I give the details of how I modeled a ‘running car’ in Android using AndEngine & Box2D physics.  This post is based on a great blog post by Emanuele Feronato on “Step by step creation of a Box2D car/truck with motors and shocks”.

You can check the video of this simulation at “Modeling a Car using AndEngine & Box2D physics
You can clone the entire project from GitHub at Wheels

So getting down to the “nuts & bolts” of  creating a car we need to create 3 components of the car

1)Car body

2)Axles (left & right)

3)Wheels (left & right)

The car body is connected to the axles through a prismatic joint. Prismatic joint, also known as ‘slider joint’, allows 2 bodies to move relative to each on a single axis of motion. Hence this joint simulates a ‘shock absorber’ effect very nicely. In fact, in the 3rd lap of my video from right to left when the car collides with the left wall you can see the car rocking on its axles. This is done as below

/* Connect the front axle to car using a prismaticJoint */

PrismaticJointDef front = new PrismaticJointDef();

front.initialize(carBody, frontAxle, frontAxle.getWorldCenter(),new Vector2(0f,1f));

front.collideConnected=false;

front.enableMotor=false;

front.enableLimit=true;

front.upperTranslation=0.5f;

front.lowerTranslation=-0.2f;

PrismaticJoint mFront = (PrismaticJoint) mPhysicsWorld.createJoint(front);

The wheels are connected to the axles through a revolute joint. A revolute joint rotates around an anchor point based on a specified motor speed and motor torque as shown below

//Connect rear wheel to rear axle using revoluteJoint
final RevoluteJointDef revoluteJointDef2 =new RevoluteJointDef();
revoluteJointDef2.initialize(wheelBody2, rearAxle, wheelBody2.getWorldCenter());
revoluteJointDef2.enableMotor =true;
revoluteJointDef2.motorSpeed =-50;
revoluteJointDef1.maxMotorTorque = 10;
rj2 =(RevoluteJoint)this.mPhysicsWorld.createJoint(revoluteJointDef2);

I wanted the car to reverse direction when it collided with either the left wall or right wall. In my original code, the car body and the walls were made of rectangle shapes and I was not able to detect the collisions. So I changed the car body and add a left wall and a right wall with sprites and checked for the collisions between these bodies. Fortunately I had done this collision detection in my app “The making of the Dino Pong Android Game”. I was able to check for collisions as shown below .

@Override
protectedvoidonManagedUpdate(finalfloat pSecondsElapsed){
// Check collisions
if(rWall.collidesWith(this)|| lWall.collidesWith(this)){

// On collision reverse speed
rj1.setMotorSpeed(-(rj1.getMotorSpeed()));
rj2.setMotorSpeed(-(rj2.getMotorSpeed()));
}

If you have done all of the above and also managed to utter the magic incantation (which I will not divulge ;-)) you should have a cute running car!  

You can check the video of this simulation at “Modeling a Car using AndEngine & Box2D physics

You can clone the entire project from GitHub at Wheels

   


Take a look at some cool simulations using AndEngine & Box2D
1. Simulating the domino effect using Box2D and AndEngine
2. Bull in a china shop – Behind the scenes in android
3. Simulating an Edge Shape in Android
4. Fun simulation of a Chain in Android
5. “Is it animal? Is it an insect?” in Android
and many more …

Find me on Google+

Simulating a Web Joint in Android

a (1) I got interested in this demo after I saw the Java demo of Box2D physics in Jbox (look in Joints). Moreover my interest in this demo was heightened as the Disney game ‘Cut the rope’ possibly uses some elements of a web joint.

Take a look at the simulation Simulating a Web Joint in Android on Youtube
You can clone the entire project from GitHub at WebJoint

The first task was to create & place Animated Sprites(face) at the corners of a rectangle. I also added distance Joints between them.

Vector2 v1 = new Vector2(p1[0]/PIXEL_TO_METER_RATIO_DEFAULT,p1[1]/PIXEL_TO_METER_RATIO_DEFAULT);

Vector2 v2 = new Vector2(p2[0]/PIXEL_TO_METER_RATIO_DEFAULT,p2[1]/PIXEL_TO_METER_RATIO_DEFAULT);

distanceJoint.initialize(body1, body2, v1, v2);

distanceJoint.collideConnected = true;

distanceJoint.dampingRatio = 1.0f;

distanceJoint.frequencyHz = 10.0f;

this.mPhysicsWorld.createJoint(distanceJoint);

}

I also had to draw connecting lines to represent the joints between the faces The challenge is to update these lines in real time as the bodies oscillate about their mean based on the damping constant. Fortunately I had done this in of my earlier demos “Creating a blob with an attitude”. The key to this is to update the connecting line to the attached bodies through the onUpdate method

@Override

publicvoid onUpdate(finalfloat pSecondsElapsed) {

super.onUpdate(pSecondsElapsed);

if(connectionLine != null)

connectionLine.setPosition(faceA.getX(),faceA.getY(),faceB.getX(),faceB.getY());

}

}

While the Animated Sprites are dynamic bodies I also created 4 pegs (static bodies) that attach to these 4 animated sprites which are suspended in a rectangle formation.

I also added a onAreaTouch listener to enable me to remove bodies interactively. This is a deviation from the demo where the user has to press a key which will remove the bodies in a pre-determined fashin.

To remove the bodies using onAreaTouch was a challenge. So when I remove an Animated Sprite I have to

  1. Remove all connecting lines to the body

  2. Destroy all the joints between the body and other bodies

TO remove the connecting lines I first tried the following

private void removeFace(AnimatedSprite face) {

if(connectionLine1 != null && connectionLine1.collidesWith(face)){

this.mScene.detachChild(connectionLine1);

connectionLine1.dispose();

connectionLine1 = null;

}

if(connectionLine2 != null && connectionLine2.collidesWith(face)){

..

But this did not quite work and it would remove only some of the lines. Then I changed it as follows based on the animated sprite that is being removed in which I specifically remove the connecting lines

if(face.equals(face1)){

Log.d(“Yes”,“Yes”);

destroyLine(connectionLine1);

destroyLine(connectionLine4);

destroyLine(connectionLine5);

}

where destroyLine() is as follow

if(line.isDisposed() == true)

return;

this.mScene.detachChild(line);

final PhysicsConnector linePhysicsConnector= this.mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(line);

this.mPhysicsWorld.unregisterPhysicsConnector(linePhysicsConnector);

line.dispose();

line = null;

}

To destroy all the distance joints which the bodies has we have to iterate through all of the joints as follows

// Determine all joints connected to Animated Sprite & destroy

ArrayList<JointEdge> jointsEdge = facePhysicsConnector.getBody().getJointList();

for(int i=0; i < jointsEdge.size(); i++){

Joint j = jointsEdge.get(i).joint;

this.mPhysicsWorld.destroyJoint(j);

j=null;

}

Finally the face is removed as follows

this.mPhysicsWorld.unregisterPhysicsConnector(facePhysicsConnector);

this.mPhysicsWorld.destroyBody(facePhysicsConnector.getBody());

this.mScene.unregisterTouchArea(face);

this.mScene.detachChild(face);

Anyway occasionally I do get a SIGSEGV in update thread if I remove face as follows lower right, lower left, upper left. Some orders work well for e.g. Upper left, lower left, lower right etc.

If you figure out what I am missing do let me know.

Take a look at the simulation Simulating a Web Joint in Android

You can clone the entire project from GitHub at WebJoint

Find me on Google+

Simulating an Edge Shape in Android

Here is a small post on how I managed to simulate an Edge Shape in Android. I wanted to do this after I saw the Java demo of Box2D in JBox2D(see RayCast). For the Edge Shape I chose a cosine curve. I used the same method I used, mentioned in my earlier post “Making of the Total Control Android Game

The simulation can be seen at Simulating an Edge Shape on YouTube
You can clone the entire project from Github at EdgeShape.

Since it is a cosine curve I place a ball shape for every point on a cosine function, close to each other to seem continuous and create a body from the Sprite with physical properties.

for (int i = 0; i < nBodies; ++i)

{

float angle = (float) ((10.0 * PI * i)/180.0);

float y1 = 300 + (float)Math.cos(angle/20) * 120;

//Log.d(“Test”,”Test” + “x:” + x1 +”y:”+ y1);

circles[i] = new Sprite(x1, y1, this.mBallTextureRegion, this.getVertexBufferObjectManager());

circlesBody[i] = PhysicsFactory.createCircleBody(this.mPhysicsWorld, circles[i], BodyType.StaticBody, FIXTURE_DEF);

this.mScene.attachChild(circles[i]);

x1 = (float) (x1 + 0.5);

}

So this can be done for every mathematical curve. I also intended to create other curves like the Archimedes Spiral and the Lemniscate. Maybe I will leave that for a rainy day!! 🙂

However, I am not sure how to create a irregular edge shape. I will probably figure that out.

The egde shape is made to be a STATIC_BODY. I then took code of creating Animated Sprites at the point where I touch from AndEngine examples (PhysicsExample.java). To make the simulation more fun I also added a Linear Impulse to the Animated Sprite.

face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion, this.getVertexBufferObjectManager());

body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, gameFixtureDef);

face.animate(200);

body.applyLinearImpulse(-200,200,pX,pY);

The effect is better if the phone is horizontal to the ground and not so great if the phone is kept vertical and the bodies do not seem to shoot off.

The simulation can be seen at Simulating an Edge Shape

You can clone the entire project from Github at EdgeShape.


Take a look at some cool simulations using AndEngine & Box2D
1. Simulating the domino effect using Box2D and AndEngine
2. Blob with an attitude(stiffness) in Android
3. The making of Total Control Android game
4. Simulating a Web Joint in Android
20. A closer look at “Robot horse on a Trot! in Android”
and many more …
Find me on Google+

The making of Dino Pong android game

DSC00016Dino Pong is my first android game from concept to completion. It is based on the android game engine AndEngine. This post gives the main hightights in the making of this fairly simple but interesting game.

Do take a look at my earlier post “Creating a simple android game using AndEngine” to understand how the basic game can be setup.

You can clone the entire project at Git Hub Dino Pong game

A video clip of Dino Pong in action can be seen here – Dino Pong clip

For the Dino Pong game I wanted the following

  1. 3 animated sprites that bounced off walls and moved with different velocities and paddle
  2. A DigitalOnScreenController that controls the paddle
  3. Collision detection between the paddle and the sprites and between the sprites themselves
  4. Points awarded for hitting a sprite with a paddle and points deducted for misses at the point of contact
  5. A game board showing hits, misses and the total score

So I created 3 animated sprites. Take a look at my earlier post on how to create an animated dino. So in the onCreateResources the 3 animated sprites and the paddle are created as below

Animated Sprites and paddle

// Create a ball

this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 64, 32, TextureOptions.BILINEAR);

this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, “face_circle_tiled.png”, 0, 0, 2, 1);

this.mBitmapTextureAtlas.load();

// Create a bront

this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 160, 64, TextureOptions.BILINEAR);

this.mBrontTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, “bront2_tiled.png”, 0, 0, 5, 1); //

this.mBitmapTextureAtlas.load();

// Create a paddle

this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTOnCextureManager(), 90, 30, TextureOptions.BILINEAR);

this.mPaddleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, “paddle1.png”, 0, 0);

this.mBitmapTextureAtlas.load();

// Create a Box face

this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 64, 64, TextureOptions.BILINEAR);

this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, “face_box_tiled.png”, 0, 0, 2, 1); // 64×32

this.mBitmapTextureAtlas.load();

In the onCreateScene the animated sprites and the paddle are added to the scene and attached to it as below

// Add ball to scene

finalfloat Y = (CAMERA_HEIGHTthis.mFaceTextureRegion.getHeight()) / 2;

ball = new Ball(X, Y, this.mFaceTextureRegion, this.getVertexBufferObjectManager());

scene.attachChild(ball);

// Add box to scene

finalfloat X1 = (CAMERA_WIDTHthis.mBoxFaceTextureRegion.getWidth()) / 2;

finalfloat Y1 = 270;

box = new Box(X1, Y1, this.mBoxFaceTextureRegion, this.getVertexBufferObjectManager());

scene.attachChild(box);

// Add paddle

finalfloat centerX = (CAMERA_WIDTHthis.mPaddleTextureRegion.getWidth()) / 2;

float centerY = 320;

paddle = new Sprite(centerX, centerY, this.mPaddleTextureRegion, this.getVertexBufferObjectManager());

final PhysicsHandler physicsHandler = new PhysicsHandler(paddle);

paddle.registerUpdateHandler(physicsHandler);

scene.attachChild(paddle);

// Create a shaking brontosaurus

finalfloat cX = (CAMERA_WIDTHthis.mBrontTextureRegion.getWidth())/2;

finalfloat cY = 50;

bront = new Bront(cX, cY, this.mBrontTextureRegion, this.getVertexBufferObjectManager());

bront.registerUpdateHandler(physicsHandler);

scene.attachChild(bront);

The paddle is registered with a physicsHandler. All the animated instances all register with the physicsHandler to be able to detect collisions.

DigitalOnScreenController for controlling paddle : For this game I have used a DigitalOnScreenController as opposed to the analog version. The digital controller seems to have a smoother movement and diagonal movements are disabled. The code for this taken from AndEngine examples.

// Add a digital on screen control

this.mDigitalOnScreenControl = new DigitalOnScreenControl(50, CAMERA_HEIGHTthis.mOnScreenControlBaseTextureRegion.getHeight() + 20, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, this.getVertexBufferObjectManager(), new IOnScreenControlListener() {

@Override

publicvoid onControlChange(final BaseOnScreenControl pBaseOnScreenControl, finalfloat pValueX, finalfloat pValueY) {

physicsHandler.setVelocity(pValueX * 100, 0);

}

});

this.mDigitalOnScreenControl.getControlBase().setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);

this.mDigitalOnScreenControl.getControlBase().setAlpha(0.5f);

this.mDigitalOnScreenControl.getControlBase().setScaleCenter(0, 128);

this.mDigitalOnScreenControl.getControlBase().setScale(1.25f);

this.mDigitalOnScreenControl.getControlKnob().setScale(1.25f);

this.mDigitalOnScreenControl.refreshControlKnobPosition();

scene.setChildScene(this.mDigitalOnScreenControl);

One of the thing I did was to disable vertical movements of the controlled object the paddle. Hence the physicsHandler sets the y value to ‘0’ as shown above

publicvoid onControlChange(final BaseOnScreenControl pBaseOnScreenControl, finalfloat pValueX, finalfloat pValueY) {

physicsHandler.setVelocity(pValueX * 100, 0);

}

Handling collisions :

As I mentioned above all the animated sprites (brontosaurus, face_circle & face_box) register with physics handler when the object is instantiated

privatestaticclass Bront extends AnimatedSprite {

privatefinal PhysicsHandler mPhysicsHandler;

floatx,y;

public Bront(finalfloat pX, finalfloat pY, final TiledTextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) {

super(pX, pY, pTextureRegion, pVertexBufferObjectManager);

this.animate(100);

this.mPhysicsHandler = new PhysicsHandler(this);

this.registerUpdateHandler(this.mPhysicsHandler);

// Change the angle to the horizontal

this.mPhysicsHandler.setVelocity(BRONT_VELOCITY, BRONT_VELOCITY);

}

If the paddle misses the sprite then when the sprite collides with the bottom wall a point is deducted

if(this.mY < 0) {

this.mPhysicsHandler.setVelocityY(BRONT_VELOCITY);

//bText.setText(“”);

} elseif(this.mY + this.getHeight() + 80 > CAMERA_HEIGHT) {

x = this.getX();

y = this.getY();

bText.setPosition(x-10,y + 20);

bText.setText(“-1”);

misses = misses – 1;

score = score -1;

missesText.setText(“Misses: “+ misses);

scoreText.setText(“Score: “ + score);

Also the sprite is restarted from the top at the same ‘x’ coordinate

// At bottom. Restart from the top

this.setPosition(x, 0);

this.mPhysicsHandler.setVelocityY(-BRONT_VELOCITY);

The collision with the paddle, face_circle & face_box are checked here

if(paddle.collidesWith(this) || this.collidesWith(paddle)){

x = this.getX();

y = this.getY();

bText.setPosition(x+10,y+10);

bText.setText(“+1”);

hits = hits + 1;

score = score + 1;

float vx = this.mPhysicsHandler.getVelocityX();

float vy = this.mPhysicsHandler.getVelocityY();

this.mPhysicsHandler.setVelocity(-vx,-vy);

}

if(ball.collidesWith(this)){

float vx = this.mPhysicsHandler.getVelocityX();

float vy = this.mPhysicsHandler.getVelocityY();

this.mPhysicsHandler.setVelocity(-vx,-vy);

}

Similarly the collision checks are done for the other 2 sprites.

When the paddle successfuly hits a sprite the points are awarded at the point of contact

if(paddle.collidesWith(this) || this.collidesWith(paddle)){

x = this.getX();

y = this.getY();

bText.setPosition(x-10,y + 20);

bText.setText(“-1”);

The score is updated simulataneously for each hit or miss

hitsText.setText(“Hits: “+ hits);

scoreText.setText(“Score: “ + score);

hits = hits + 1;

score = score + 1;

Additional tweaks

  1. The size of the DigitalOnScreenController was shrunk by half as it seemed oversized for my Android phone

  2. A box is drawn within which the sprites can bounce off allowing space for the score at the bottom

final Line line1 = new Line(0, 0, 320, 0, 5, this.getVertexBufferObjectManager());

final Line line2 = new Line(320, 0, 320, 400, 5, this.getVertexBufferObjectManager());

final Line line3 = new Line(320, 400, 0, 400, 5, this.getVertexBufferObjectManager());

final Line line4 = new Line(0, 400, 0, 0, 5, this.getVertexBufferObjectManager());

// Add bounded rectangle to scene

scene.attachChild(line1);

scene.attachChild(line2);

scene.attachChild(line3);

scene.attachChild(line4);

  1. The velocities of the 3 sprites are made slightly different

  2. The x & y components of the velocity of the face_circle and face_box differ to enable a slightly different angle of motion.

A video clip of Dino Pong in action can be seen here – Dino Pong clip

You can clone the entire project at Git Hub  Dino Pong game

or the complete code can be downloaded at DinoPong.zip

Issues: One of the issues I see is that when the paddle hits the middle of any sprite then the sprite appears to get locked and does not bounce off. Sometimes 2 sprites also get into this ‘deadly embrace’ before getting themselves released. It appears that successive collisions happen before the velocity and position can be changed hence resulting in this lock up. Any ideas on fixing this are welcome.

Do let me know your thoughts on this game.

Find me on Google+