我在iOS中用彈跳球實施了一個基本的box2d項目,但在實際到達地面之前球似乎彈起。在每次逐步反彈時,它似乎都接近底部,最終落在地面上。我注意到發生了什麼視頻:http://f.cl.ly/items/1S06373Z1l2w1z243E0k/Bounce.m4v在Box2D彈跳地球之前彈跳
這裏是我設置好一切:
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;
我認爲,問題是在可視化,即你的球形象不符合物理球。你能證明,你如何畫球? – Pavel 2013-03-02 10:43:33
你可以顯示你用來創建球體的代碼嗎?我想知道爲什麼你明確地更新它的位置(通常是物理引擎中的一個壞主意),而不是讓box2d的引力處理它。 – 2013-03-02 15:16:09
@Pavel你完全正確,請參閱下面的答案。 – 2013-03-02 15:32:48