由于Box2D是最多只能创建八边形形状的刚体(虽然可以修改源码增添边数),尤其是只能创建凸多边形,要是想创建凹多边形,最好就是将其拆分为多个凹多边形,转为创建复合形状的刚体。
从实现上来看,只是多了几个ShapeDef,然后body在调用了多个CreateShape方法
注:
b2PolygonDef:SetAsOrientedBox方法的参数:半宽,半高,位置,角度(子形状)
b2CircleDef:localPosition属性:位置(子形状)
b2PolygonDef的多边形比较消耗资源
一般尽可能用Circle跟Box配合旋转创建复杂图形
个人感觉最强大的还是三角形,想想神奇的3D引擎就知道了
源码:
三角形 AND 三角形:
bodyDef = new b2BodyDef();
bodyDef.position.Set(275 / RATIO, ( i * -120 - 600) / RATIO);
bodyDef.angle = (Math.random() * 360) * Math.PI / 180;
boxDef1 = new b2PolygonDef();
boxDef1.vertexCount = 3;
boxDef1.vertices[0] = new b2Vec2(0, 0);
boxDef1.vertices[1] = new b2Vec2( -30 / RATIO, 30 / RATIO);
boxDef1.vertices[2] = new b2Vec2(0, -30 / RATIO);
boxDef1.density = 2.0;
boxDef2 = new b2PolygonDef();
boxDef2.vertexCount = 3;
boxDef2.vertices[0] = new b2Vec2(0, 0);
boxDef2.vertices[1] = new b2Vec2(0, -30 / RATIO);
boxDef2.vertices[2] = new b2Vec2(30 / RATIO, 30 / RATIO);
boxDef2.density = 2.0;
body = world.CreateBody(bodyDef);
body.CreateShape(boxDef1);
body.CreateShape(boxDef2);
body.SetMassFromShapes();
圆形 AND 矩形
bodyDef = new b2BodyDef();
bodyDef.position.Set(100 / RATIO, ( i * -120 - 100) / RATIO);
bodyDef.angle = (Math.random() * 360) * Math.PI / 180;
boxDef1 = new b2PolygonDef();
boxDef1.SetAsBox(60 / 2 / RATIO, 60 / 2 / RATIO);
boxDef1.density = 2.0;
circleDef = new b2CircleDef();
circleDef.radius = 30 / RATIO;
circleDef.density = 2.0;
circleDef.localPosition = new b2Vec2(0, -30 / RATIO);
body = world.CreateBody(bodyDef);
body.CreateShape(boxDef1);
body.CreateShape(circleDef);
body.SetMassFromShapes();
矩形 AND 矩形 AND ...
bodyDef = new b2BodyDef();
bodyDef.position.Set(400 / RATIO, (i * -120 - 100) / RATIO);
bodyDef.angle = (Math.random() * 360) * Math.PI / 180;
boxDef1 = new b2PolygonDef();
boxDef1.SetAsBox(80 / 2 / RATIO, 20 / 2 / RATIO);
boxDef1.density = 2.0;
boxDef2 = new b2PolygonDef();
boxDef2.SetAsOrientedBox(20 / 2 / RATIO, 60 / 2 / RATIO, new b2Vec2( -30 / RATIO, -40 / RATIO), 0);
boxDef2.density = 2.0;
boxDef3 = new b2PolygonDef();
boxDef3.SetAsOrientedBox(20 / 2 / RATIO, 60 / 2 / RATIO, new b2Vec2(30 / RATIO, -40 / RATIO), 0);
boxDef3.density = 2.0;
boxDef4 = new b2PolygonDef();
boxDef4.SetAsOrientedBox(10 / 2 / RATIO, 20 / 2 / RATIO, new b2Vec2( -15 / RATIO, -60 / RATIO), 0);
boxDef4.density = 2.0;
boxDef5 = new b2PolygonDef();
boxDef5.SetAsOrientedBox(10 / 2 / RATIO, 20 / 2 / RATIO, new b2Vec2(15 / RATIO, -60 / RATIO), 0);
boxDef5.density = 2.0;
body = world.CreateBody(bodyDef);
body.CreateShape(boxDef1);
body.CreateShape(boxDef2);
body.CreateShape(boxDef3);
body.CreateShape(boxDef4);
body.CreateShape(boxDef5);
body.SetMassFromShapes();
运行结果截图:
运行结果: