2

我需要为身体创建椭圆形状,但不明白如何在 box2d 中制作它。

任何想法如何使用b2PolygonShape大量顶点来做到这一点。

4

1 回答 1

5

** 选项1 **

使用带有两个固定装置的身体:第一个是中心圆形,以赋予身体一些质量。第二个是椭圆,其顶点由链形组成。

第一个fixture 可以让你让body 像一个有质量的body 一样工作,而第二个fixture 可以让你正确处理碰撞。

我最近做了一个轮盘赌的例子。我发布了下面的代码来创建它。将半径的常量值 (OUTER_RADIUS) 替换为在 wikipedia 上找到的椭圆的极坐标形式。

void MainScene::CreateBody()
{
   const float32 INNER_RADIUS = 2.50;
   const float32 OUTER_RADIUS = 3.0;
   const float32 BALL_RADIUS = 0.1;
   const uint32 DIVISIONS = 36;

   Vec2 position(0,0);

   // Create the body.
   b2BodyDef bodyDef;
   bodyDef.position = position;
   bodyDef.type = b2_dynamicBody;
   _body = _world->CreateBody(&bodyDef);
   assert(_body != NULL);

   // Now attach fixtures to the body.
   FixtureDef fixtureDef;
   fixtureDef.density = 1.0;
   fixtureDef.friction = 1.0;
   fixtureDef.restitution = 0.9;
   fixtureDef.isSensor = false;

   // Inner circle.
   b2CircleShape circleShape;
   circleShape.m_radius = INNER_RADIUS;
   fixtureDef.shape = &circleShape;
   _body->CreateFixture(&fixtureDef);

   // Outer shape.
   b2ChainShape chainShape;
   vector<Vec2> vertices;
   const float32 SPIKE_DEGREE = 2*M_PI/180;
   for(int idx = 0; idx < DIVISIONS; idx++)
   {
      float32 angle = ((M_PI*2)/DIVISIONS)*idx;
      float32 xPos, yPos;

      xPos = OUTER_RADIUS*cosf(angle);
      yPos = OUTER_RADIUS*sinf(angle);
      vertices.push_back(Vec2(xPos,yPos));
   }
   vertices.push_back(vertices[0]);
   chainShape.CreateChain(&vertices[0], vertices.size());
   fixtureDef.shape = &chainShape;
   _body->CreateFixture(&fixtureDef);

}

您还可以查看此帖子以了解轮盘赌(加上图片优势)解决方案。

选项#2 您可以创建一个三角形风扇,而不是使用链/边缘形状。获得椭圆的顶点后,您可以执行以下操作:

b2Vec2 triVerts[3];
triVerts[0] = Vec2(0,0);
for(int idx = 1; idx < vertices.size(); idx++)
{
   b2PolygonShape triangle;
   fixtureDef.shape = &triangle;
   // Assumes the vertices are going around
   // the ellipse clockwise as angle increases.
   triVerts[1] = vertices[idx-1];
   triVerts[2] = vertices[idx];
   triangle.Set(triVerts,3);
   _body->CreateFixture(&fixtureDef);
}

这个有帮助吗?

于 2013-12-13T02:22:06.287 回答