2014-01-18 50 views
1

我想做一個場景,那裏有一個「鐘擺」,連續振盪,不停。爲了更清晰起見,我上傳了一張圖片。所以我嘗試使用Box2D關節。例如:Box2D:繩擺(不停)

RevoluteJointDef revDef = new RevoluteJointDef(); 
    revDef.initialize(ball, box, ball.getWorldCenter()); 
    revDef.lowerAngle = 0 * MathUtils.degreesToRadians; 
    revDef.upperAngle = 180 * MathUtils.degreesToRadians; 
    revDef.enableLimit = true; 
    revDef.maxMotorTorque = 10.0f; 
    revDef.motorSpeed = 2.0f; 
    revDef.enableMotor = true; 

    revoluteJoint = (RevoluteJoint)world.createJoint(revDef); 

但它不起作用。如果我評論界限和電機線,我會得到和我注意到的結果相同的結果。儘管電機已啓用,但似乎不起作用。

P.S.按下按鈕,用戶釋放盒子時,電機必須停止。所以箱子由於重力而落到地上。

有人可以幫助我嗎? 謝謝!

Scene image

+0

另請參閱此[示例](http://stackoverflow.com/a/11233735/230513)使用'FloatSpring'。 – trashgod

回答

1

我不認爲你需要爲這個旋轉接頭,但繩子接頭(b2RopeJoint)。旋轉關節將使兩個物體圍繞單個點旋轉。繩索接頭將像鐘擺一樣擺動另一個。

您需要將單擺連接到一個靜態物體上。然後在你想要墜落時切斷繩索接頭。如果重力開啓並且沒有任何阻滯力,那麼鐘擺應無限期地持續(或根據數字長時間持續)。

Take a look at this post剛剛完成這樣的事情。請注意,代碼也發佈在github here上。在那種情況下,爲了約束身體,增加了兩個額外的繩索關節,以便它不能超出最初的擺動結束。我不認爲你需要這些。

要創建擺自己,用這樣的:

// Calculate the local position of the 
    // top of screen in the local space 
    // of the ground box. 
    CCSize scrSize = CCDirector::sharedDirector()->getWinSize(); 
    b2Vec2 groundWorldPos = b2Vec2((scrSize.width/2)/PTM_RATIO,(scrSize.height)/PTM_RATIO); 
    b2Vec2 groundLocalPos = m_pGround->GetLocalPoint(groundWorldPos); 

    // Now create the main swinging joint. 
    b2RopeJointDef jointDef; 
    jointDef.bodyA = m_pGround; 
    jointDef.bodyB = body; 
    jointDef.localAnchorA = groundLocalPos; 
    jointDef.localAnchorB = b2Vec2(0.0f,0.0f); 
    jointDef.maxLength = (groundWorldPos-body->GetWorldCenter()).Length(); 
    jointDef.collideConnected = true; 
    world->CreateJoint(&jointDef); 

注:這是在C++中,而不是Java(用於libgdx),但該方法應該是完善的,你只需要地圖將「 - >」拖到「。」上。需要的地方。

在我的例子,它結束了看起來像這樣(像其他發佈答案解放):

enter image description here

對您有幫助?

+0

謝謝@FuzzyBunnySlippers!這是我在jBox2D上工作的第二天......我應該「有信心」。 – fpellegrino

+1

@fpellegrino祝你好運。請隨時查看我網站上的其他一些帖子(http://www.nlideas.com)。另外,iForce2d網站上有很多很好的教程(https://www.iforce2d.net/b2dtut/)。 – FuzzyBunnySlippers

+0

如何在我的遊戲中繪製繩索關節?顯然,如果我刪除了DebugRender,繩子和其他身體模型就隱藏起來了。所以對於遊戲的某些元素,我使用圖像(精靈),但對於繩子?這個精靈應該與關節的位置和傾斜度相同...... – fpellegrino