2013-03-02 133 views
0

我在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; 
+0

我認爲,問題是在可視化,即你的球形象不符合物理球。你能證明,你如何畫球? – Pavel 2013-03-02 10:43:33

+0

你可以顯示你用來創建球體的代碼嗎?我想知道爲什麼你明確地更新它的位置(通常是物理引擎中的一個壞主意),而不是讓box2d的引力處理它。 – 2013-03-02 15:16:09

+0

@Pavel你完全正確,請參閱下面的答案。 – 2013-03-02 15:32:48

回答

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]; 
0

如果聲明的球體動態

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

和初始化世界智慧h一些重力值(您已經完成),您不必手動設置球體的位置。沒有看到所有你的代碼,我的直覺是你已經宣佈球已經動態了,你的手動位置更新與box2d的重力衝突。視頻似乎顯示球被重力拉下來,同時其位置被人爲地轉移。我建議完全刪除分配給self.ball.position的行 - 直接設置這樣的物理體的位置通常不是一個好主意。