如何在box2d中创建椭圆形状?

时间:2012-04-05 16:53:47

标签: c++ box2d shape

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

如何使用包含大量顶点的b2PolygonShape来完成的任何想法。

1 个答案:

答案 0 :(得分:5)

**选项#1 **

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

第一个夹具允许你让身体像一个有一定质量的身体,而第二个夹具可以让你正确处理碰撞。

我最近为轮盘赌做了一个例子。我发布了下面的代码来创建它。将半径的常量值(OUTER_RADIUS)替换为椭圆的极坐标形式found here on 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);

}

您还可以查看this post轮盘赌(加上图片善)解决方案。

选项#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);
}

这有用吗?