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 Total Control Android game

tc-1This game of Total Control was one of those games I played when I was a kid when there were no Smartphone or iPods. It was a simple, circular toy with small balls which you had to slowly nudge to the innermost circle. I have been wanting to replicate this game on Android for some time.

The game can be  downloaded from Google Play at Total Control
The Total Control project can be cloned from Git Hub at Total Control

I had decided to use AndEngine & Box2D physics for this. I was under the assumption that creating those concentric circles would be a breeze with AndEngine and Box2D physics. However it took me some time to figure out how to create these circles. Eventually I realized that each circle could be created by computing the circumference of the concentric circle and placing tiny circle bodies. Each of these tiny circles are of type BodyType.StaticBody. So they have physical properties of a ring on which other bodies can roll. With this solved the rest of the implementation was quite straight forward.
– Small colored balls were placed in different spots in the concentric circles.
– Small gaps were created like the real game to move to an inner circle

Finally the whole game uses the Accelaration Sensor and uses Gravity for movement of the balls much like the real game.

tc-2

I also wanted to include AdMob into the game. Here is a good link at WikiHow with all the steps for adding AdMob to your app.

However the above link provides a method of placing the Ad in your desired layout’s XML file. Since my game was based on AndEngine the method to place an Ad in the game uses the FrameLayout. The complete code is given here the AndEngine Forum. To test the working of the Ads make sure you add the code

// REQUEST an ad (Test ad) //
AdRequest adRequest = new AdRequest();
adRequest.addTestDevice(“<Your device Id from the Console”); //Comment this line when publishing
adView.loadAd(adRequest);

You should get your device id when your run your application in Eclipse in the Console tab. When you run the app you should see the Ad. You may have to adjust your app to allow for teh Ad. I had to move and shrink my Game to allow for the Ad display at the bottom.

You can download the game from Google Play at Total Control
The Total Control project can be cloned from Git Hub at Total Control

Find me on Google+

Blob with an attitude in Android

DSC00044This post is an enhanced version of my earlier blob post Creating a blob in Android with Box2D physics engine and AndEngine.. To introduce tautness to the overall blob structure I used revoluteJoint between adjacent bodies as follows

}

// Create a revoluteJoint between adjacent bodies – Lacks stiffness

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

final RevoluteJointDef revoluteJointDef = new RevoluteJointDef();

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

revoluteJointDef.enableMotor = false;

revoluteJointDef.motorSpeed = 0;

revoluteJointDef.maxMotorTorque = 0;

this.mPhysicsWorld.createJoint(revoluteJointDef);

}

// Create a revolute joint between first and last bodies

final RevoluteJointDef revoluteJointDef = new RevoluteJointDef();

revoluteJointDef.initialize(circleBody[0], circleBody[19], circleBody[0].getWorldCenter());

revoluteJointDef.enableMotor = false;

revoluteJointDef.motorSpeed = 0;

revoluteJointDef.maxMotorTorque = 0;

this.mPhysicsWorld.createJoint(revoluteJointDef);

The motorSpeed, maxMotorTorque is set to 0 and the enableMotor is set to false. However I found that this joint still lacks stiffness.

So I replaced the revoluteJoint with the weldJoint which is probably more appropriate

// Create a weldJoint between adjacent bodies – Weld Joint has more stiffness

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

final WeldJointDef weldJointDef = new WeldJointDef();

weldJointDef.initialize(circleBody[i], circleBody[i-1], circleBody[i].getWorldCenter());

this.mPhysicsWorld.createJoint(weldJointDef);

}

// Create a weld joint between first and last bodies

final WeldJointDef weldJointDef = new WeldJointDef();

weldJointDef.initialize(circleBody[0], circleBody[19], circleBody[0].getWorldCenter());

this.mPhysicsWorld.createJoint(weldJointDef);

Here are clips of the the Blob with more attitude

Blob with attitude – Part 1

Blob with attitude – Part 2

You can clone the project from Github at Blob_v1

Find me on Google+

Creating a Blob in Android using Box2D physics engine and AndEngine

DSC00037Here is a short post on my attempt to create a Blob using Box2D physics engine and AndEngine. This demo tries to recreate the Blob Joint at GwtBox2D Showcase. This Blob Joint demo in Java uses a ConstantVolume Joint for creating the Blob. For my blob I use a distanceJoint for maintaining the shape of the Blob.

Here is the clip of the blob in action : Blob clip
You can clone the project from Github from the Blob code

A Blob is created in the initial shape of an ellipse as follows
// Add 20 circle bodies around an ellipse
for (int i=0; i<nBodies; ++i) {
FIXTURE_DEF = PhysicsFactory.createFixtureDef(30f, 0.5f, 0.5f)
Vector2 v1 = new Vector2(x1,y1);
final VertexBufferObjectManager vb = this.getVertexBufferObjectManager();
circle[i] = new AnimatedSprite(x1, y1, this.mCircleFaceTextureRegion, this.getVertexBufferObjectManager());
circleBody[i] = PhysicsFactory.createCircleBody(this.mPhysicsWorld, circle[i], BodyType.DynamicBody, FIXTURE_DEF);


}

A distance Joint is created between every body as follows

// Create a distanceJoint between every other day
for(int i= 0;i < nBodies-1; i++) {
for(int j=i+1; j 0) {
connectionLine[i] = new Line(centers[i][0],centers[i][1],centers[i-1][0],centers[i-1][1],lineWidth,this.getVertexBufferObjectManager());
connectionLine[i].setColor(0.0f,0.0f,1.0f);
this.mScene.attachChild(connectionLine[i]);
}

// Join the first body with the last body
if(i == 19){
connectionLine[0] = new Line(centers[0][0],centers[0][1],centers[19][0],centers[19][1],lineWidth,this.getVertexBufferObjectManager());
connectionLine[0].setColor(.0f,.0f,1.0f);
this.mScene.attachChild(connectionLine[0]);
}

The connecting lines move along with the moving shapes as below
// Update connection line so that the line moves along with the body
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(circle[i], circleBody[i], true, true) {
@Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
for(int i=1;i < nBodies;i++) {
connectionLine[i].setPosition(circle[i].getX(),circle[i].getY(),circle[i-1].getX(),circle[i-1].getY());

} connectionLine[0].setPosition(circle[0].getX(),circle[0].getY(),circle[19].getX(),circle[19].getY());
}
}
);

So here is the clip of the blob in action : Blob clip
You can clone the project from Github from the Blob code

Some cool simulations using AndEngine & Box2D
1. Simulating the domino effect using Box2D and AndEngine
2. Simulating a Web Joint in Android
3. Modeling a Car in Android
4. Fun simulation of a Chain in Android
5. A closer look at “Robot horse on a Trot! in Android”
and many more
Find me on Google+