码迷,mamicode.com
首页 > 其他好文 > 详细

16--Box2D使用(二、显示物理世界)

时间:2014-08-01 15:49:51      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   os   strong   io   

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

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

bubuko.com,布布扣

        再声明一个变量

    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);
}
       现在运行看看效果吧

bubuko.com,布布扣

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

      让物理世界运行起来

      添加函数

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;
}

       再运行看看效果

bubuko.com,布布扣

16--Box2D使用(二、显示物理世界),布布扣,bubuko.com

16--Box2D使用(二、显示物理世界)

标签:style   blog   http   color   使用   os   strong   io   

原文地址:http://www.cnblogs.com/BlueBeauty/p/3884862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!