创建组合的刚体

要创建组合刚体,可以分别创建多个形状定义,然后在同一个刚体实例上调用多次CreateShape(b2ShapeDef)。核心代码如下:

1。先定义刚体定义(用来创建组合刚体),设置刚体位置,并创建刚体实例。

var bodyDef:b2BodyDef = new b2BodyDef();

bodyDef.position.Set(275 / PhyOption.PHYSCALE, 0 / PhyOption.PHYSCALE);

var body:b2Body = PhyOption.getInstance().world.CreateBody(bodyDef);

PhyOption是我自定义的类是一个单例,里面保存有物理世界的长度单位,重力常量,world引用等。

2。创建第一个组合进去的形状(凸多边形)

var rectShapeDef:b2PolygonDef = new b2PolygonDef();
rectShapeDef.restitution = 0.2;
rectShapeDef.friction = 0.3;
rectShapeDef.density = 3;
rectShapeDef.SetAsOrientedBox(rectWidth / 2 / PhyOption.PHYSCALE, rectHeight / 2 / PhyOption.PHYSCALE,new b2Vec2(0,0),0);

此处与创建单独的刚体不同,此处使用的是SetAsOrientedBox方法,而单独创建刚体时用的是SetAsBox方法

3。创建第二个组合的形状(圆形)

var circleShapeDef:b2CircleDef = new b2CircleDef();
circleShapeDef.friction = 0.1;
circleShapeDef.density = 1;
circleShapeDef.restitution = 0.4;
circleShapeDef.radius = circleRadius/PhyOption.PHYSCALE;
circleShapeDef.localPosition = new b2Vec2(0, -32.5 / PhyOption.PHYSCALE);

此处与创建单独的圆形刚体不同,此处多了一个属性药赋值,即localPosition。

4。最后创建刚体形状,根据形状计算质量

body.CreateShape(rectShapeDef);
body.CreateShape(circleShapeDef);
body.SetMassFromShapes();

5。利用调试功能看效果

var sp:Sprite = new Sprite();
addChild(sp);
var dbg:b2DebugDraw = new b2DebugDraw();
dbg.m_sprite = sp;
dbg.m_drawFlags = b2DebugDraw.e_shapeBit;
dbg.m_drawScale = PhyOption.PHYSCALE;
dbg.m_fillAlpha = 0.5;
dbg.m_alpha = 0.5;
PhyOption.getInstance().world.SetDebugDraw(dbg);

6。最后进行迭代模拟,需在enterFrame事件中调用

 PhyOption.getInstance().world.Step(PhyOption.STEP, PhyOption.ITERATION);

 

posted @ 2010-04-08 22:40  ywxgod  阅读(474)  评论(0编辑  收藏  举报