In 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+
15 thoughts on “Fun simulation of a Chain in Android”