0

我在 iOS 中用一个弹跳球实现了一个基本的 box2d 项目,但球似乎在它真正到达地面之前弹跳了。在每次渐进式反弹时,它似乎都更接近底部并最终落在地面上。我拍了一段视频:http: //f.cl.ly/items/1S06373Z1l2w1z243E0k/Bounce.m4v

这是我设置所有内容的地方:

CGSize screenSize = self.view.bounds.size;

// Define the gravity vector.
b2Vec2 gravity;
gravity.Set(0.0f, -9.81f);

bool doSleep = true;

// Construct a world object, which will hold and simulate the rigid bodies.
world = new b2World(gravity);
world->SetAllowSleeping(doSleep);
world->SetContinuousPhysics(true);

b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0);

b2Body *groundBody = world->CreateBody(&groundBodyDef);
b2EdgeShape groundEdge;
b2FixtureDef boxShapeDef;
boxShapeDef.shape = &groundEdge;

//bottom
groundEdge.Set(b2Vec2(0,0), b2Vec2(screenSize.width/PTM_RATIO, 0));
groundBody->CreateFixture(&boxShapeDef);

// left wall
groundEdge.Set(b2Vec2(0,0), b2Vec2(0,screenSize.height/PTM_RATIO));
groundBody->CreateFixture(&boxShapeDef);

// top
groundEdge.Set(b2Vec2(0, screenSize.height/PTM_RATIO),
               b2Vec2(screenSize.width/PTM_RATIO, screenSize.height/PTM_RATIO));
groundBody->CreateFixture(&boxShapeDef);

// right wal
groundEdge.Set(b2Vec2(screenSize.width/PTM_RATIO, screenSize.height/PTM_RATIO),
               b2Vec2(screenSize.width/PTM_RATIO, 0));
groundBody->CreateFixture(&boxShapeDef);

//ball
b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(self.ball.position.x/PTM_RATIO, self.ball.position.y/PTM_RATIO);
ballBodyDef.userData =  (__bridge void *)_ball;
body = world->CreateBody(&ballBodyDef);

b2CircleShape circle;
circle.m_radius = 60.0/PTM_RATIO;

b2FixtureDef ballShapeDef;
ballShapeDef.shape = &circle;
ballShapeDef.density = 0.8f;
ballShapeDef.friction = 0.0f;
ballShapeDef.restitution = 0.8f;
body->CreateFixture(&ballShapeDef);

然后这就是我每 1/60 秒运行一次以更新位置

int32 velocityIterations = 8;
int32 positionIterations = 1;

world->Step(1.0f/60.0f, velocityIterations, positionIterations);

CGPoint newCenter = CGPointMake(body->GetPosition().x * PTM_RATIO,
                                self.view.bounds.size.height - body->GetPosition().y * PTM_RATIO);
self.ball.position = newCenter;
4

2 回答 2

0

如果您将球体声明为动态的

b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
// finish creating...

并使用一些重力值(您已经完成)初始化世界,您根本不需要手动设置球体的位置。在没有看到所有代码的情况下,我的直觉是您已经将球声明为动态的,并且您的手动位置更新与 box2d 的重力相冲突。视频似乎显示球被重力拉下,同时人为地改变了它的位置。我建议self.ball.position完全删除分配给的行 - 像这样直接设置物理体的位置通常不是一个好主意。

于 2013-03-02T15:19:32.677 回答
0

我发现了问题所在。屏幕上的球是一个 CALayer,当它改变它的位置时,它使用了隐式动画。现在以这种方式设置位置时效果很好

[CATransaction begin];
[CATransaction setDisableActions:YES];
CGPoint newCenter = CGPointMake(body->GetPosition().x * PTM_RATIO,
                                self.view.bounds.size.height - body->GetPosition().y * PTM_RATIO);
self.ball.position = newCenter;
[CATransaction commit];
于 2013-03-02T15:31:32.240 回答