一般而言,我们画出的刚体是显示不出来的,但是通过我们创建的b2World的成员函数DrawDebugData就可以实现。
首先需要将头文件GLES-Render.h加入到我们的工程当中。
首先记录我们创建物理世界的变量(scene的成员变量)
b2World* world;
然后在初始化时进行设置,因为不一定需要画出设计刚体的所有细节在init函数或者scene'的构造函数中进行使用
GLESDebugDraw* m_debugDraw = new GLESDebugDraw(PTM_RATIO);
world->SetDebugDraw(m_debugDraw);
uint32 flags = 0;
flags += b2Draw::e_shapeBit;
// flags += b2Draw::e_jointBit;
// flags += b2Draw::e_aabbBit;
// flags += b2Draw::e_pairBit;
// flags += b2Draw::e_centerOfMassBit;
m_debugDraw->SetFlags(flags);
之后在重载draw函数
void Box2DTestLayer::draw()
{
//
// IMPORTANT:
// This is only for debug purposes
// It is recommend to disable it
//
CCLayer::draw();
#if CC_ENABLE_BOX2D_INTEGRATION
// ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
kmGLPushMatrix();
world->DrawDebugData();
kmGLPopMatrix();
#endif
}
这样我们画出的刚体就能实现了正常显示了,但是还有一点,在物理世界中刚体进行移动怎么办?当物体受到力作用时,刚体的位置变换应该如何显示?
这时我们需要正常开启
scheduleUpdate();//模拟时间步更新,系统调用update函数
在update函数中进行定义
void Box2DTestLayer::update(float dt)
{
//It is recommended that a fixed time step is used with Box2D for stability
//of the simulation, however, we are using a variable time step here.
//You need to make an informed choice, the following URL is useful
//http://gafferongames.com/game-physics/fix-your-timestep/
int velocityIterations = 8;
int positionIterations = 1;
// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);//box2d通过step更新动画,8是速度迭代次数,第三个是位置迭代次数
}
这样就可以实现我们的刚体显示了