鉴于最近工作涉及JBox2D,打算围绕testbed的sample来做些细致的了解。也希望自己学习的同时跟大家探讨。
虽然box2d的手册已经详细的描述了hello box2d的代码,本篇也主要是简单用android实现,没有绘制部分,但是很清楚的描述了box2d运行的基本情况。
</pre><pre name="code" class="java">
- /********************************/
- /*Box2D v2.2.0 User Manual 文中代码的android实现版本*/
- /*本例调用JBox2d4Android_2.1.2.jar*/
- /*下载<span style="background-color: rgb(255, 255, 255); ">JBox2d4Android_2.1.2.jar </span> 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. */
- @Override
- public 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);
- }
-
-
- }
-
- }
-
- }