0

我正在尝试在 Cocos2d + Box2d 中开发 iOS 游戏。我想在 Box2D 中使用椭圆夹具。我尝试使用 b2Capsule 形状,但它不完全是我想要的,因为碰撞不正确。以前有人做过吗?

4

2 回答 2

0

我也使用了近似值。这有一些性能缺陷,但我猜没有什么大不了的。代码(Flash ActionScript 3,但您应该能够轻松移植):

var vertices:Vector.<b2Vec2> = new Vector.<b2Vec2>();
var a:Number = _image.width / 2 / PhysicsVals.RATIO;
var b:Number = _image.height / 2 / PhysicsVals.RATIO;
var segments:int = ellipse_approximation_vertices_count; (the more the more precise shape is, but the more time it takes to do collision detection)

var segment:Number = 2 * Math.PI / segments;

for (var i:int = 0; i < segments; i++)
{
    vertices.push(new b2Vec2(a * Math.cos(segment * i), b * Math.sin(segment * i)));
}

var shape:b2PolygonShape = new b2PolygonShape();
shape.SetAsVector(vertices, vertices.length);

var fixtureDef:b2FixtureDef = new b2FixtureDef();       
fixtureDef.shape = shape;
于 2013-07-11T18:40:50.790 回答
0

对于 Box2D 中的特定形状,您将不得不对原始多边形进行三角剖分(在您的情况下,您将在其中保留一定数量的顶点的椭圆)。

为此,您可以使用http://code.google.com/p/poly2tri/上的 poly2tri 出色的约束 Delaunay 三角剖分, 非常简单。这是我得到三角形的方法:

- (NSArray*) triangulate:(NSArray*)verticesArray
{

NSMutableArray* outputTriangles = [[[NSMutableArray alloc] init] autorelease];

p2t::CDT* triangulationContainer;
vector<p2t::Triangle*> p2tTriangles;
vector< vector<p2t::Point*> > polylines;
vector<p2t::Point*> polyline;

for (hOzPoint2D *point in verticesArray) {
    polyline.push_back(new p2t::Point([point x], [point y]));
}

polylines.push_back(polyline);
triangulationContainer = new p2t::CDT(polyline);
triangulationContainer->Triangulate();
p2tTriangles = triangulationContainer->GetTriangles();

for (int i = 0; i < p2tTriangles.size(); i++) {

    p2t::Triangle& t = *p2tTriangles[i];

    p2t::Point& a = *t.GetPoint(0);
    p2t::Point& b = *t.GetPoint(1);
    p2t::Point& c = *t.GetPoint(2);

    [outputTriangles addObject:[NSArray arrayWithObjects:
                                [hOzPoint2D point2DWithDoubleX:a.x doubleY:a.y],
                                [hOzPoint2D point2DWithDoubleX:b.x doubleY:b.y],
                                [hOzPoint2D point2DWithDoubleX:c.x doubleY:c.y], nil]];

}

delete triangulationContainer;

for(int i = 0; i < polylines.size(); i++) {
    vector<p2t::Point*> poly = polylines[i];
    FreeClear(poly);
}

return [outputTriangles copy];

}

hOzPoint2D 这里是我的自定义点类,但你可以传递任意几个坐标。您甚至不必输出 NSArray :您可以将此方法插入到您的身体创建方法中。注意 poly2tri 有一些限制:

  • 您的多边形中不能有两次相同的点;
  • 多边形不能是自相交的;
  • ...

阅读 poly2tri 页面以了解更多信息。

生成的数组包含作为固定装置附加到同一主体的三角形。

于 2013-03-30T10:05:58.567 回答