• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            隨筆 - 132  文章 - 51  trackbacks - 0
            <2010年12月>
            2829301234
            567891011
            12131415161718
            19202122232425
            2627282930311
            2345678

            常用鏈接

            留言簿(7)

            隨筆分類

            隨筆檔案

            文章分類

            文章檔案

            cocos2d-x

            OGRE

            OPenGL

            搜索

            •  

            最新評論

            閱讀排行榜

            評論排行榜

            根據(jù)上一節(jié)的教程,我用C++更改了教程,我用的cocos2d-2.0-rc2-x-2.0.1版本,略微有些不同,都是小細節(jié),直接貼上代碼
            HelloWorldScene.h

            #ifndef __HELLOWORLD_SCENE_H__
            #define __HELLOWORLD_SCENE_H__

            #include 
            <Box2D/Box2D.h>
            #include 
            "cocos2d.h"
            #include 
            <list>
            using std::list;

            class MyContact
            {
            public:
              b2Fixture
            * fixtureA;
              b2Fixture
            * fixtureB;
            }
            ;

            // Contact listener
            class MyContactListener : public b2ContactListener
            {
              
            // Callbacks for derived classes.
              virtual void BeginContact(b2Contact* contact) 
              

                
            if (contact)
                
            {
                  MyContact mc;
                  mc.fixtureA 
            = contact->GetFixtureA();
                  mc.fixtureB 
            = contact->GetFixtureB();

                  contact_list.push_back(mc);
                }

                B2_NOT_USED(contact); 
              }

              
            virtual void EndContact(b2Contact* contact) 
              

                contact_list.clear();
                B2_NOT_USED(contact); 
              }

              
            virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
              
            {
                B2_NOT_USED(contact);
                B2_NOT_USED(oldManifold);
              }

              
            virtual void PostSolve(const b2Contact* contact, const b2ContactImpulse* impulse)
              
            {
                B2_NOT_USED(contact);
                B2_NOT_USED(impulse);
              }


            public:
              std::list
            <MyContact> contact_list;
            }
            ;

            class HelloWorld : public cocos2d::CCLayer
            {
            public:
                HelloWorld();
                
            ~HelloWorld();
                
            // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
                virtual bool init();  

                
            // there's no 'id' in cpp, so we recommand to return the exactly class pointer
                static cocos2d::CCScene* scene();
                
                
            // a selector callback
                void menuCloseCallback(CCObject* pSender);
                    
                
            virtual void ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);
                
            virtual void ccTouchesMoved(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);
                
            virtual void ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);
                
            virtual void ccTouchesCancelled(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);

                cocos2d::CCTMXLayer 
            *baseLayer;

                
            // implement the "static node()" method manually
                LAYER_CREATE_FUNC(HelloWorld);

            private:
              
            // Update per second
              void secondUpdate(float dt)  
              
            {  
                spawnCat();
              }

              
            void tick(float dt);

              
            // spawn a car
              void spawnCar();

              
            // spawn a car
              void spawnCat();

              
            // Sprite move over call back
              void spriteDone(cocos2d::CCNode* sender);

              
            // Add contact b2box for sprite
              void addBoxBodyForSprite(cocos2d::CCSprite* sprite);

              b2World
            * world;
              MyContactListener
            * contactListener; // Contact event listener
            }
            ;

            #endif // __HELLOWORLD_SCENE_H__

             

             

            HelloWorldScene.cpp

            #include "HelloWorldScene.h"

            USING_NS_CC;
            USING_NS_CC_EXT;
            using namespace std;

            #define TILE_SIZE 32
            #define PT_RATIO 32  // 這個數(shù)一般定義為: 32.0,在box 世界中 是以 米 為單位的,這里是將坐標兌換為box世界中的米,即除以 PTM_RATIO

            //--------------------------------------------

            HelloWorld::HelloWorld()
            {

            }


            HelloWorld::
            ~HelloWorld()
            {
              
            if(world)
                delete world;
            }


            CCScene
            * HelloWorld::scene()
            {
              
            // 'scene' is an autorelease object
              CCScene *scene = CCScene::create();

              
            // 'layer' is an autorelease object
              HelloWorld *layer = HelloWorld::create();

              
            // add layer as a child to scene
              scene->addChild(layer);

              
            // return the scene
              return scene;
            }


            enum 
            {
                kTagTileMap 
            = 1,
            }
            ;

            CCLabelTTF
            * pLabel;
            // on "init" you need to initialize your instance
            bool HelloWorld::init()
            {
              
            //////////////////////////////
              // 1. super init first
              if ( !CCLayer::init() )
              
            {
                
            return false;
              }


              pLabel 
            = CCLabelTTF::create("Collsion""Arial"24);
              CCSize size 
            = CCDirector::sharedDirector()->getWinSize();

              
            // position the label on the center of the screen
              pLabel->setPosition( ccp(size.width / 2, size.height - 50) );

              
            // add the label as a child to this layer
              this->addChild(pLabel, 10);

              
            // create physic world
              b2Vec2 gravity(0,0);
              world 
            = new b2World(gravity);
              world
            ->SetAllowSleeping(false);

              contactListener 
            = new MyContactListener();
              world
            ->SetContactListener(contactListener);

              spawnCar();
                
              schedule(schedule_selector(HelloWorld::tick));
              schedule(schedule_selector(HelloWorld::secondUpdate), 
            1.f);
              setTouchEnabled(
            true);
              
            return true;
            }



            void HelloWorld::tick(float dt)
            {
              
            if (world)
                world
            ->Step(dt, 1010);

              
            // 基于cocos2d的精靈位置來更新box2d的body位置
              for(b2Body* b = world->GetBodyList(); b; b = b->GetNext())
              
            {
                
            if (b->GetUserData() != NULL)
                
            {
                  CCSprite
            * sprite = (CCSprite*)b->GetUserData();
                  
            if (sprite)
                  
            {
                    b2Vec2 pt 
            = b2Vec2((float)(sprite->getPosition().x / PT_RATIO), (float)(sprite->getPosition().y / PT_RATIO));
                    
            float angle = (CCFloat)CC_DEGREES_TO_RADIANS(sprite->getRotation());
                    b
            ->SetTransform(pt, angle);
                  }

                }

              }


              std::list
            <b2Body*> toDestroy_list;

              
            for( std::list<MyContact>::iterator it = contactListener->contact_list.begin(); 
                                          it 
            != contactListener->contact_list.end();
                                          
            ++it)
              
            {
                MyContact
            & contact = *it;

                b2Body
            * bodyA = contact.fixtureA->GetBody();
                b2Body
            * bodyB = contact.fixtureB->GetBody();

                CCSprite
            * sa = (CCSprite*)bodyA->GetUserData();
                CCSprite
            * sb = (CCSprite*)bodyB->GetUserData();
                
            if (sa && sb)
                
            {
                  
            if (sa->getTag() == 1 && sb->getTag() == 2)
                    toDestroy_list.push_back(bodyB);
                  
            else if (sa->getTag() == 2 && sa->getTag() == 1)
                    toDestroy_list.push_back(bodyA);
                }

              }

              
              
            // Destroy contact item.
              std::list<b2Body*>::iterator it = toDestroy_list.begin();
              
            while(it != toDestroy_list.end())
              
            {
                
            if ((*it)->GetUserData() != NULL)
                
            {
                  CCSprite
            * sprite = (CCSprite*)((*it)->GetUserData());
                  
            if (sprite)
                  
            {
                    removeChild(sprite, 
            true);
                  }

                  world
            ->DestroyBody(*it);
                }


                
            ++it;
              }


              toDestroy_list.clear();
              
            }


            void HelloWorld::spawnCar()
            {
              CCSprite
            * car = CCSprite::spriteWithFile("images/car.png");
              car
            ->setPosition(ccp(100,100));

              car
            ->runAction(CCRepeatForever::actionWithAction((CCActionInterval*)CCSequence::actions(
                CCMoveTo::actionWithDuration(
            1.0f, ccp(300,100)),
                CCMoveTo::actionWithDuration(
            1.0f, ccp(200,200)),
                CCMoveTo::actionWithDuration(
            1.0f, ccp(100,100)),
                NULL
                )));

              addBoxBodyForSprite(car);
              
            this->addChild(car, 11);
            }


            void HelloWorld::spawnCat()
            {
              CCSize winSize 
            = CCDirector::sharedDirector()->getWinSize();
              CCSprite
            * cat = CCSprite::spriteWithFile("images/cat.png");

              
            float minY = cat->getContentSize().height/2;
              
            float maxY = winSize.height - cat->getContentSize().height/2;
              
            float y = minY + rand() % (int)(maxY - minY);

              
            float startX = winSize.width + cat->getContentSize().width/2;
              
            float endX = -cat->getContentSize().width/2;

              CCPoint startPos 
            = ccp(startX, y);
              CCPoint endPos 
            = ccp(endX, y);

              cat
            ->setPosition(startPos);

              cat
            ->runAction(CCSequence::actions(CCMoveTo::actionWithDuration(10.f, endPos), 
                CCCallFuncN::actionWithTarget(
            this, callfuncN_selector(HelloWorld::spriteDone)), NULL));


              addBoxBodyForSprite(cat);
              addChild(cat, 
            12);
            }


            void HelloWorld::addBoxBodyForSprite(cocos2d::CCSprite* sprite)
            {
              
            //PTM_RATIO  ,這個數(shù)一般定義為: 32.0,在box 世界中 是以 米 為單位的,這里是將坐標兌換為box世界中的米,即除以 PTM_RATIO

              
            // Create physic body for cat
              b2PolygonShape polygon;
              polygon.SetAsBox((
            float)sprite->getContentSize().width/PT_RATIO/2, (float)sprite->getContentSize().height/PT_RATIO/2);

              b2FixtureDef spriteShapeDef;
              spriteShapeDef.shape 
            = &polygon;
              spriteShapeDef.density 
            = 10.f;
              spriteShapeDef.isSensor 
            = true;   // 對象之間有碰撞檢測但是又不想讓它們有碰撞反應

              b2BodyDef bd;
              bd.type 
            = b2_dynamicBody;
              bd.position 
            = b2Vec2((float)(sprite->getPosition().x / PT_RATIO),
                (
            float)(sprite->getPosition().y /PT_RATIO));
              bd.userData 
            = sprite;

              b2Body
            * spriteBody = world->CreateBody(&bd);
              spriteBody
            ->CreateFixture(&spriteShapeDef);
            }




            void HelloWorld::spriteDone(CCNode* sender)
            {
              
            // sprites被銷毀的時候,我們需要銷毀Box2d的body
              CCSprite* sprite = dynamic_cast<CCSprite*>(sender);
              
            if (sprite)
              
            {
                b2Body
            * spriteBody = NULL;
                
            for(b2Body* b = world->GetBodyList(); b; b=b->GetNext())
                
            {
                  
            if (b->GetUserData() != NULL)
                  
            {
                    CCSprite
            * curSprite = (CCSprite*)b->GetUserData();
                    
            if (curSprite == sprite)
                    
            {
                      spriteBody 
            = b;

                      removeChild(sprite, 
            true);
                      world
            ->DestroyBody(spriteBody);
                      
            break;
                    }

                  }


                  
            //if (spriteBody)
                  
            //{
                  
            //  world->DestroyBody(spriteBody);
                  
            //}

                  
            // removeChild(sprite, true);
                }

              }

            }


            void HelloWorld::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
            {
              CCSetIterator iter 
            = pTouches->begin();
              
            for (; iter != pTouches->end(); iter++)
              
            {
                CCTouch
            * pTouch = (CCTouch*)(*iter);
                CCPoint pos 
            = pTouch->locationInView();
                pos 
            = CCDirector::sharedDirector()->convertToGL(pos);

              }

            }


            void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
            {
              CCSetIterator iter 
            = pTouches->begin();
              
            for (; iter != pTouches->end(); iter++)
              
            {
                CCTouch
            * pTouch = (CCTouch*)(*iter);
                CCPoint pos 
            = pTouch->locationInView();

                CCPoint touchLocation 
            = pTouch->locationInView();    
                CCPoint prevLocation 
            = pTouch->previousLocationInView();    
                
            /*    touchLocation = CCDirector::sharedDirector()->convertToGL( touchLocation );
                prevLocation = CCDirector::sharedDirector()->convertToGL( prevLocation );
                
                CCPoint diff = ccpSub(touchLocation, prevLocation);
                
                CCNode *node = getChildByTag(kTagTileMap);
                CCPoint currentPos = node->getPosition();

                node->setPosition( ccpAdd(currentPos, diff) )
            */
            ;
              }

            }


            void HelloWorld::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
            {
              CCSetIterator iter 
            = pTouches->begin();
              
            for (; iter != pTouches->end(); iter++)
              
            {
                CCTouch
            * pTouch = (CCTouch*)(*iter);
              }

            }


            void HelloWorld::ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent)
            {
              ccTouchesEnded(pTouches, pEvent);
            }



            查看源代碼

            posted on 2012-07-12 15:21 風輕云淡 閱讀(9681) 評論(3)  編輯 收藏 引用

            FeedBack:
            # re: cocos2d-x 使用box2d來做碰撞檢測(且僅用來做碰撞檢測)(二) 2012-09-22 11:01 jasonllinux
            你好,請問box2d的include如何設置的
            我在 eclipse的include里面add了box2d的路徑
            但是發(fā)現(xiàn)編譯的時候時好時壞的  回復  更多評論
              
            # re: cocos2d-x 使用box2d來做碰撞檢測(且僅用來做碰撞檢測)(二) 2014-04-01 16:32 zngto
            為什么我把這段執(zhí)行后監(jiān)聽不到剛體碰撞呢?  回復  更多評論
              
            久久婷婷午色综合夜啪| 亚洲精品高清国产一久久| 蜜臀av性久久久久蜜臀aⅴ麻豆| 996久久国产精品线观看| AAA级久久久精品无码区| 久久婷婷五月综合成人D啪| 国产亚洲美女精品久久久久狼| 亚洲国产成人久久综合野外| 狠狠色婷婷久久一区二区三区| 久久夜色撩人精品国产| 91精品国产色综合久久| 亚洲午夜福利精品久久 | 亚洲国产精品无码久久98| 国产精品久久免费| 国内精品久久国产| 国产精品久久久天天影视香蕉| 色偷偷88888欧美精品久久久| 久久91精品综合国产首页| 久久精品国产亚洲AV无码偷窥| 久久综合伊人77777麻豆| 99精品伊人久久久大香线蕉| 久久久久99精品成人片试看| 亚洲国产日韩欧美综合久久| 久久久精品人妻无码专区不卡| 久久亚洲国产午夜精品理论片| 亚洲精品午夜国产VA久久成人| 少妇被又大又粗又爽毛片久久黑人| 99麻豆久久久国产精品免费| 奇米影视7777久久精品| 中文字幕无码久久精品青草| 久久免费视频6| 欧美性大战久久久久久| 99久久综合国产精品二区| 久久精品国产影库免费看| 99久久这里只有精品| 久久91精品国产91久久麻豆| 国产精品99久久免费观看| 成人国内精品久久久久一区| 国产精品久久久久天天影视| 99久久人人爽亚洲精品美女| 国产毛片久久久久久国产毛片|