鑒於最近工作涉及JBox2D,打算圍繞testbed的sample來做些細緻的瞭解。也希望自己學習的同時跟大家探討。
雖然box2d的手冊已經詳細的描述了hello box2d的代碼,本篇也主要是簡單用android實現,沒有繪製部分,但是很清楚的描述了box2d啟動並執行基本情況。
/********************************//*Box2D v2.2.0 User Manual 文中代碼的android實現版本*//*本例調用JBox2d4Android_2.1.2.jar*//*下載JBox2d4Android_2.1.2.jar http://download.csdn.net/detail/z1074971432/3831279*//********************************/import org.jbox2d.collision.shapes.PolygonShape;import org.jbox2d.common.Vec2;import org.jbox2d.dynamics.Body;import org.jbox2d.dynamics.BodyDef;import org.jbox2d.dynamics.BodyType;import org.jbox2d.dynamics.FixtureDef;import org.jbox2d.dynamics.World;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.view.View;public class Box2d_lesson1_hellobox2dActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(new helloBox2dView(this));}class helloBox2dView extends View {public helloBox2dView(Context context) {super(context);World world;/** Creating a World */{Vec2 gravity = new Vec2(0, -10f);boolean dosleep = true;world = new World(gravity, dosleep);}/** Creating a Ground Box */{// Bodies are built using the following steps:// Step 1. Define a body with position, damping, etc.BodyDef groundBodyDef = new BodyDef();groundBodyDef.position.set(0.0f, 1.0f);// Step 2. Use the world object to create the body.Body groundBody = world.createBody(groundBodyDef);// Step 3. Define fixtures with a shape, friction, density, etc.PolygonShape groundBox = new PolygonShape();groundBox.setAsBox(50.0f, 1.0f);// Step 4. Create fixtures on the body.groundBody.createFixture(groundBox, 0.0f);}/** Creating a Dynamic Body */Body body;{BodyDef bodyDef = new BodyDef();bodyDef.type = BodyType.DYNAMIC;bodyDef.position.set(0.0f, 4.0f);body = world.createBody(bodyDef);PolygonShape dynamicBox = new PolygonShape();dynamicBox.setAsBox(1.0f, 1.0f);FixtureDef fixtureDef = new FixtureDef();fixtureDef.shape = dynamicBox;fixtureDef.density = 1.0f;fixtureDef.friction = 0.3f;body.createFixture(fixtureDef);}/** Simulating the World (of Box2D) */{float timeStep = 1.0f / 60.0f;int velocityIterations = 6;int positionIterations = 2;for (int i = 0; i < 60; ++i){world.step(timeStep, velocityIterations, positionIterations);Vec2 position = body.getPosition();float angle = body.getAngle();System.out.printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);}}}}