物体的形状,大小,材质,密度,弹性等属性由定制器描述(fixture),有人翻译成夹具。物体碰撞后会根据各自的定制器做出反应。定制器主要属性如下
-形状
-弹性
-摩擦
-密度
物体间的碰撞依赖物体的形状,box2d可以定义圆弧,矩形和多边形。
{ // 圆形 bodyDef.type = b2_dynamicBody; bodyDef.position.Set(2.0, 3.0); // body position b2Body* circleBody = mWorld->CreateBody(&bodyDef); b2CircleShape circleShape; circleShape.m_p.Set(0, 0); // 圆心,相对其 body position circleShape.m_radius = 0.5; // 半径 circleBody->CreateFixture(&circleShape,1); } { // 三角形 bodyDef.type = b2_dynamicBody; bodyDef.position.Set(4.0, 3.0); // body position b2Body* triangleBody = mWorld->CreateBody(&bodyDef); b2PolygonShape triangleShape; b2Vec2 vertices[3]; // 顶点数组 vertices[0].Set(-0.5, -0.5); vertices[1].Set(0.5, 0.5); vertices[2].Set(0, 1); triangleShape.Set(vertices, 3); triangleBody->CreateFixture(&triangleShape,1); } { // 矩形 bodyDef.position.Set(8.0, 3.0); b2Body* rectangle = mWorld->CreateBody(&bodyDef); b2PolygonShape rectangleShape; rectangleShape.SetAsBox(1, 2); // 设置矩形半高半宽 rectangle->CreateFixture(&rectangleShape,1); }
其实矩形也是多边形,看矩形的SetAsBox函数的实现
void b2PolygonShape::SetAsBox(float32 hx, float32 hy) { m_vertexCount = 4; m_vertices[0].Set(-hx, -hy); m_vertices[1].Set( hx, -hy); m_vertices[2].Set( hx, hy); m_vertices[3].Set(-hx, hy); m_normals[0].Set(0.0f, -1.0f); m_normals[1].Set(1.0f, 0.0f); m_normals[2].Set(0.0f, 1.0f); m_normals[3].Set(-1.0f, 0.0f); m_centroid.SetZero(); }
注意,圆心的坐标是相对于其body position而言的,多边形的顶点坐标也是相对body position而言。多边形顶点在右手坐标系中逆时针旋转。
box2d默认的多边形最大边是8,如果你要更多的顶点多边形,需要改这个值,在Box2D/Common/b2Settings.h里面定义的一个宏
/// The maximum number of vertices on a convex polygon. You cannot increase /// this too much because b2BlockAllocator has a maximum object size. #define b2_maxPolygonVertices 8