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+