2011-11-02 80 views
0

我第一次使用box2d,並且通過hello world教程設置了我的形狀。通過direct2d渲染box2d形狀

我創建一個框,因此:

b2BodyDef bodyDef; 
bodyDef.type = b2_kinematicBody; 
bodyDef.position.Set(7.0f, 7.0f); 
bodyDef.angle = 0; 

m_body = m_world->CreateBody(&bodyDef); 

b2PolygonShape shape; 
shape.SetAsBox(1.5f, 0.5f); 

b2FixtureDef fixtureDef; 
fixtureDef.shape = &shape; 
fixtureDef.density = 1.0f; 

m_body->CreateFixture(&fixtureDef); 

現在我準備渲染這個盒子,所以我呼籲:

b2Vec2 pos = m_body->GetPosition(); 

在這一點上,我需要調用m_renderTarget-> SetTransform()使用pos的值,但我無法弄清楚如何正確渲染框。我曾嘗試:

m_renderTarget->SetTransform(D2D1::Matrix3x2F::Translation(pos.x * 30, pos.y * 30)); 
m_renderTarget->DrawRectangle(D2D1::RectF(0.0f, 0.0f, 3.0f * 30.0f, 1.0f * 30.0f), m_brush); 

和圓:

bodyDef.type = b2_dynamicBody; 
bodyDef.position.Set(7.0f, 1.0f); 

m_circleBody = m_world->CreateBody(&bodyDef); 

b2CircleShape circleShape; 
circleShape.m_p.Set(0.0f, 0.0f); 
circleShape.m_radius = 0.5f; 

fixtureDef.shape = &circleShape; 

m_circleBody->CreateFixture(&fixtureDef); 

而且呈現圓:

b2Vec2 circlePos = m_circleBody->GetPosition(); 

    mpRenderTarget->SetTransform(D2D1::Matrix3x2F::Translation(circlePos.x * 30.0f, circlePos.y * 30.0f)); 

    mpRenderTarget->DrawEllipse(D2D1::Ellipse(D2D1::Point2F(0.0f, 0.0f), 30.0f, 30.0f), m_brush); 
+0

你是什麼意思沒有運氣?什麼都沒有繪製?東西被吸引,但它的錯誤? –

+0

繪製了形狀,但物理屬性不正確(其他動態形狀會穿過應該是實心的區域)。 – user987280

+0

選取一個看似正在落下的物體,併發布物理{位置,尺寸}以及圖形{平移,矩形座標} –

回答

0

您還沒有繪製您的矩形正確居中。矩形的中心在左上角。

m_renderTarget->DrawRectangle(D2D1::RectF(0.0f, 0.0f, 3.0f * 30.0f, 1.0f * 30.0f), m_brush); 

爲了正確居中,你應該離開= - 右,頂值=漢字像這樣

m_renderTarget->DrawRectangle(D2D1::RectF(-1.5 * 30.f, -0.5 * 30.f, 1.5f * 30.0f, 0.5f * 30.0f), m_brush); 

這裏有一個圖表,解釋爲什麼中心是很重要的:

diagram illustrating the importance of centering

物理上你可以正確地表示兩種形狀,但是在圖形上你會在不知不覺中給矩形添加一個偏移量。此外,您的比例關閉:您假設矩形的1 = 30像素,圓的0.5 = 30像素。一致性是仿真的關鍵,所以您應該將D2D1 :: Ellipse的半徑降低到15。

+0

看起來你是正確的,但也需要在DrawEllipse調用中將半徑改爲15.0f。 – user987280