我需要为 body 创建椭圆形状,但不明白如何在 box2d 中制作它。
关于如何不通过使用具有大量顶点的b2PolygonShape
来做到这一点的任何想法。
最佳答案
选项#1
使用带有两个固定装置的主体:第一个是中心圆形,以赋予主体一定的质量。第二种是椭圆形,顶点由链形构成。
第一个 fixture 允许你让 body 表现得像一个有一定质量的 body,而第二个 fixture 允许你正确处理碰撞。
我最近做了一个轮盘赌的例子。我发布了下面的代码来创建它。将半径的常数值 (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 = ▵
// 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);
}
这有帮助吗?
关于c++ - 如何在 box2d 中创建椭圆形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10032756/