通过direct2d渲染box2d形状

时间:2011-11-02 05:35:39

标签: directx physics box2d

我第一次使用box2d,我通过hello world教程设置了我的形状。

我正在创建一个框:

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();

此时,我需要使用pos的值调用m_renderTarget-> SetTransform(),但我无法弄清楚如何正确渲染框。我试过了:

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);

1 个答案:

答案 0 :(得分:0)

您没有正确地将矩形绘制在中心位置。矩形的中心位于左上角。

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

为了正确居中,你应该让Left = -Right,Top = -Bottom像这样

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。