zoukankan      html  css  js  c++  java
  • 16--Box2D使用(二、显示物理世界)

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

             %Cocos_Home%samplesCppTestCppClassesBox2DTestBed中找到,将这两个文件拷贝到项目中并引入工程中。

    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秒

  • 相关阅读:
    分时段查询数据
    优秀产品经理的7大核心技能
    控制台打印螺旋数组
    强大的jquery,再次让我为之鼓掌——三维展示插件
    立象条码打印机PPLB类单双标签打印
    一次与德国程序员的交流
    用ASP为Discuz扩展点小功能
    GDI+ 小破孩动画
    回应YeanJay同学jQuery按钮改变DIV背景色
    C# Dock Style 设置
  • 原文地址:https://www.cnblogs.com/BlueBeauty/p/3884862.html
Copyright © 2011-2022 走看看