首页 > 代码库 > box2d——1.tiles瓦片积木
box2d——1.tiles瓦片积木
【调试渲染】
将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; }
【效果图和下载】
代码下载地址
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。