【调试渲染】
将TestCpp里Box2DTestBed的GLES-Render.h/cpp添加到项目中,声明绘制变量:GLESDebugDrawmDebugDraw。
【创建世界】
// 根据重力创建世界 b2Vec2 gravity; gravity.Set(0.0f, -10.0f); mWorld = new b2World(gravity); // 设置调试渲染和碰撞侦听 mWorld->SetDebugDraw(&mDebugDraw); mWorld->SetContactListener(this); // 创建地面身体 b2BodyDef goundBodyDef; mGroundBody = mWorld->CreateBody(&goundBodyDef); // 设置物理更新函数 schedule(schedule_selector(CTilesLayer::tick));【创建物体】
mFixtureCount = 0;
b2Timer timer;
// 创建静态的矩形(1个body多个shape、fixture)
{
float32 a = 0.5f;
b2BodyDef bd;
bd.position.y = -a;
b2Body* ground = mWorld->CreateBody(&bd);
int32 N = 200;
int32 M = 10;
b2Vec2 position;
position.y = 0.0f;
for (int32 j = 0; j < M; ++j)
{
position.x = -N * a;
for (int32 i = 0; i < N; ++i)
{
b2PolygonShape shape;
shape.SetAsBox(a, a, position, 0.0f);
ground->CreateFixture(&shape, 0.0f);
++mFixtureCount;
position.x += 2.0f * a;
}
position.y -= 2.0f * a;
}
}
// 创建动态的矩形(一个shape多个body)
{
float32 a = 0.5f;
b2PolygonShape shape;
shape.SetAsBox(a, a);
b2Vec2 x(-7.0f, 0.75f);
b2Vec2 y;
b2Vec2 deltaX(0.5625f, 1.25f);
b2Vec2 deltaY(1.125f, 0.0f);
enum { e_count = 20 };
for (int32 i = 0; i < e_count; ++i)
{
y = x;
for (int32 j = i; j < e_count; ++j)
{
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position = y;
b2Body* body = mWorld->CreateBody(&bd);
body->CreateFixture(&shape, 5.0f);
++mFixtureCount;
y += deltaY;
}
x += deltaX;
}
}【设置物理显示】
// 设置显示 mTextLine = 30; setScale(15); setAnchorPoint( ccp(0,0) ); CCSize screenSize = CCDirector::sharedDirector()->getWinSize(); setPosition( ccp(screenSize.width/2, screenSize.height/3) ); // 设置物理 uint32 flags = 0; flags += b2Draw::e_shapeBit; flags += b2Draw::e_jointBit; mDebugDraw.SetFlags(flags); mWorld->SetWarmStarting(true); mWorld->SetContinuousPhysics(true); mWorld->SetSubStepping(false);
void CTilesLayer::draw()
{
CCLayer::draw();
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
kmGLPushMatrix();
// 绘制物理数据
mWorld->DrawDebugData();
kmGLPopMatrix();
CHECK_GL_ERROR_DEBUG();
}【更新物理】
void CTilesLayer::tick(float dt)
{
// 显示
const b2ContactManager& cm = mWorld->GetContactManager();
int32 height = cm.m_broadPhase.GetTreeHeight();
int32 leafCount = cm.m_broadPhase.GetProxyCount();
int32 minimumNodeCount = 2 * leafCount - 1;
float32 minimumHeight = ceilf(logf(float32(minimumNodeCount)) / logf(2.0f));
mDebugDraw.DrawString(5, mTextLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight));
mTextLine += 15;
mWorld->Step(1/60.0f, 8, 3);
mWorld->DrawDebugData();
mDebugDraw.DrawString(5, mTextLine, "create time = %6.2f ms, fixture count = %d",
mCreateTime, mFixtureCount);
mTextLine += 15;
}
box2d——1.tiles瓦片积木,布布扣,bubuko.com
原文:http://blog.csdn.net/adfansong/article/details/26013209