我正在尝试为 Box2d、Cocos2d 和 Android 创建一个简单的测试。我所需要的只是将一个身体放在屏幕上,让它对重力做出反应。我到处看了看,有很好的非 Android 应用程序教程,但没有一个对 Android 工作有影响。任何人都可以帮忙吗?
这是我正在使用的代码。我拿了它,并从这里轻轻修改:http ://www.expobrain.net/2012/05/12/box2d-physics-simulation-on-android/
创造世界:
World world = new World(new Vec2(2.0f, 8.0f), false);
这就是我创建身体的方式:
public void setupBallBody() {
CGSize size = CCDirector.sharedDirector().winSize();
CGPoint pos = CGPoint.make(size.width / 1.2f, size.height / 1.2f);
// Create Dynamic Body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC;
bodyDef.position.set(screenToWorld(pos));
ballBody = world.createBody(bodyDef);
MassData md = new MassData();
md.mass = 5;
ballBody.setMassData(md);
// Create Shape
CircleShape ballShape = new CircleShape();
ballShape.m_radius = SMILE_RADIUS;
// Create fixture
FixtureDef ballFixture = new FixtureDef();
ballFixture.shape = ballShape;
ballFixture.density = SMILE_DENSITY;
ballFixture.friction = SMILE_FRICTION;
ballFixture.restitution = SMILE_RESTITUTION;
// Assign fixture to Body
ballBody.createFixture(ballFixture);
// Set sprite
final CCSprite ballSprite = CCSprite.sprite("ball.jpg");
ballSprite.setPosition(pos);
addChild(ballSprite, 0);
ballBody.setUserData(ballSprite);
}
这是我的“tick”方法(我不确定它是否是重力工作的一部分,但为了完整起见,我将其包含在此处。)
public void tick(float dt) {
synchronized (world) {
world.step(1/60, 10, 10);
}
// Update sprites
for (Body b = world.getBodyList(); b != null; b = b.getNext()) {
if(b == ballBody) {
CCSprite ballSprite = (CCSprite)ballBody.getUserData();
if(ballSprite != null) {
ballSprite.setPosition(worldToScreen(ballBody.getPosition())));
ballSprite.setRotation(-1.0f * (float)Math.toDegrees((ballBody.getAngle())));
}
}
}
}