• <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
            <2011年4月>
            272829303112
            3456789
            10111213141516
            17181920212223
            24252627282930
            1234567

            常用鏈接

            留言簿(7)

            隨筆分類

            隨筆檔案

            文章分類

            文章檔案

            cocos2d-x

            OGRE

            OPenGL

            搜索

            •  

            最新評(píng)論

            閱讀排行榜

            評(píng)論排行榜

            根據(jù)上一節(jié)的教程,我用C++更改了教程,我用的cocos2d-2.0-rc2-x-2.0.1版本,略微有些不同,都是小細(xì)節(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  // 這個(gè)數(shù)一般定義為: 32.0,在box 世界中 是以 米 為單位的,這里是將坐標(biāo)兌換為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的精靈位置來(lái)更新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  ,這個(gè)數(shù)一般定義為: 32.0,在box 世界中 是以 米 為單位的,這里是將坐標(biāo)兌換為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;   // 對(duì)象之間有碰撞檢測(cè)但是又不想讓它們有碰撞反應(yīng)

              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被銷毀的時(shí)候,我們需要銷毀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 風(fēng)輕云淡 閱讀(9681) 評(píng)論(3)  編輯 收藏 引用

            FeedBack:
            # re: cocos2d-x 使用box2d來(lái)做碰撞檢測(cè)(且僅用來(lái)做碰撞檢測(cè))(二) 2012-09-22 11:01 jasonllinux
            你好,請(qǐng)問(wèn)box2d的include如何設(shè)置的
            我在 eclipse的include里面add了box2d的路徑
            但是發(fā)現(xiàn)編譯的時(shí)候時(shí)好時(shí)壞的  回復(fù)  更多評(píng)論
              
            # re: cocos2d-x 使用box2d來(lái)做碰撞檢測(cè)(且僅用來(lái)做碰撞檢測(cè))(二) 2014-04-01 16:32 zngto
            為什么我把這段執(zhí)行后監(jiān)聽不到剛體碰撞呢?  回復(fù)  更多評(píng)論
              

            只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。
            網(wǎng)站導(dǎo)航: 博客園   IT新聞   BlogJava   博問(wèn)   Chat2DB   管理


            久久成人国产精品二三区| 精品伊人久久久| 久久亚洲精品无码AV红樱桃| 一本大道久久香蕉成人网| 久久精品国产99久久丝袜| 亚洲欧美日韩精品久久| 国产精品久久成人影院| 久久狠狠高潮亚洲精品| 久久夜色精品国产欧美乱| 日韩人妻无码精品久久久不卡| 久久久久av无码免费网| 久久精品日日躁夜夜躁欧美| 久久久久久久久久久| 97久久婷婷五月综合色d啪蜜芽| 久久人人爽人人爽人人av东京热| 色综合久久夜色精品国产| 一本久久综合亚洲鲁鲁五月天亚洲欧美一区二区 | 日日躁夜夜躁狠狠久久AV| 精品国产乱码久久久久久呢| 久久人人爽人人爽人人片AV麻烦| 久久综合亚洲色HEZYO社区| 亚洲国产精品无码成人片久久| 亚洲色婷婷综合久久| 丰满少妇高潮惨叫久久久| 精品一区二区久久久久久久网站| 久久精品国产只有精品2020| 日本精品久久久久中文字幕| 久久91精品综合国产首页| 久久这里有精品| 久久精品人人做人人爽97| 四虎国产永久免费久久| 久久九九免费高清视频| 久久亚洲AV无码精品色午夜| 亚洲国产欧美国产综合久久| 久久精品天天中文字幕人妻| 久久免费线看线看| 亚洲日本久久久午夜精品| 亚洲va中文字幕无码久久不卡| 久久青青草原精品影院| 天堂无码久久综合东京热| 久久天天躁狠狠躁夜夜avapp |