我在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;
答案 0 :(得分:0)
如果您将球体声明为动态
b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
// finish creating...
用一些重力值(你已经完成)初始化世界,你根本不需要手动设置球体的位置。如果没有看到所有你的代码,我的预感就是你已经宣布球已经动态了,你的手动位置更新与box2d的引力相冲突。视频似乎显示球被人工移位时被重力拉下来。我建议完全删除分配给self.ball.position
的行 - 直接设置物理主体的位置通常不是一个好主意。
答案 1 :(得分: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];