深秋

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

         在上一篇文章中我们创建了的一个物理世界,当物理世界中的刚体一个也没有显示出来。为显示物理世界中的物体,我们需要引入GLES-Render(调试Box2D使用)。这两个文件可以再

         %Cocos_Home%\samples\Cpp\TestCpp\Classes\Box2DTestBed中找到,将这两个文件拷贝到项目中并引入工程中。

image

        再声明一个变量

    b2World* world;
    b2Body* wallBody ;

    float32 wallLineOffset ;

    GLESDebugDraw* m_debugDraw;  //调试物理世界绘制对象

       声明两个函数

    void printDebugDraw(bool isPrint);
    virtual void draw();

       printDebugDraw实现

void HelloWorld::printDebugDraw(bool isPrint){
    if(!isPrint)
        return;
    //根据像素与米的转换系数创建调试绘制对象
    m_debugDraw = new GLESDebugDraw( PIXEL_TO_METER );
    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 HelloWorld::draw()  
{  
    CCLayer::draw();

    ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );

    kmGLPushMatrix();

    world->DrawDebugData();

    kmGLPopMatrix();

}

        修改createWorld

void HelloWorld::createWorld()
{
    b2Vec2 gravity;
    gravity.Set(0.0f,-9.0f);   //物理世界重力向量,这里创建一个向下的重力向量
    b2BodyDef* bodydef = new b2BodyDef();
    world = new b2World(gravity);    //根据重力向量创建物理世界对象

    world->SetAllowSleeping(true);   //允许休眠    
    world->SetWarmStarting(true);    //初始状态将受到重力影响

    printDebugDraw(true);
}
       现在运行看看效果吧

若水GIF截图_2014年8月1日13点48分46秒

     物理世界的物体就显示出来了,但那几个球怎么没有动呢?不用急,是因为我们还没有让物理世界运行起来。

      让物理世界运行起来

      添加函数

void HelloWorld::update(float dt)
{
    //速度迭代次数
    int velocityIterations = 8;
    //位置迭代次数
    int positionIterations = 1;

    world->Step(dt, velocityIterations, positionIterations);  //dt为时间步长

}

       在init方法中添加代码

bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }

    wallLineOffset = 0.5;

    this->createWorld();
    this->createWall();
    this->createBall();

    this->scheduleUpdate(); //不断调用update函数 


     ……
   

    return true;
}

       再运行看看效果

若水GIF截图_2014年8月1日14点2分56秒

posted on 2014-08-01 14:04  深秋  阅读(757)  评论(0编辑  收藏  举报