Cocos2d-x game development parkour (8) Object Management Collision Detection

Source: Internet
Author: User

The principle of Object Management is as follows:

The ObjectManager class is a singleton class, and only one object instance exists globally. During initialization, two arrays (CCArray) are created to save the gold coins and rocks. Why do we need to save it, because when the map is overloaded, we need to destroy invisible objects. Gold coins and rocks are randomly added. Each gold coin and rock has a map index. That is to say, they are on the first maps and are deleted based on the index.

My blog: http://blog.csdn.net/dawn_moon; welcome to repost

CCArray has a traversal macro CCARRAY_FOREACH. If you add or delete an object during traversal, an error occurs. Here, I use a temporary CCArray to save the object to be deleted, then, traverse the temporary array to delete the source array, and finally clear the temporary array.

CCArray * tempCoins = CCArray: create (); CCArray * tempRocks = CCArray: create (); CCObject * itor; // when traversing CCArray, addition and deletion operations cannot be performed, otherwise, an error will occur. // The process is completed in two steps. During the first traversal, the object to be deleted is saved to a temporary CCArray. // In the second step, the temporary CCArray is traversed, delete the objects from the source group, and clear the temporary array CCARRAY_FOREACH (mCoins, itor) {Coin * coin = dynamic_cast
 
  
(Itor); if (coin! = NULL) & (coin-> getMap () = mapIndex) {tempCoins-> addObject (coin); coin-> destroy () ;}} CCARRAY_FOREACH (tempCoins, itor) {mCoins-> fastRemoveObject (itor);} tempCoins-> removeAllObjects ();
 

This class is initialized in the init of PlayScene:

    ObjectManager* ObjM= ObjectManager::sharedObjectManager();    ObjM->initManager(spriteBatch, mWorld);    ObjM->setObjectToMap(1, mMapManager->getMapWidth());

Then add gold coins and rocks in update of PlayScene,

// If a map is overloaded, decommissioned gold coins and rocks will be reclaimed and new gold coins and rocks will be added. if (mMapManager-> chechReloadMap (mLastEyeX) {ObjectManager: Export dobjectmanager () -> recycleObjectOfMap (mMapManager-> getCurMapIndex ()-1); ObjectManager: Export dobjectmanager ()-> setObjectToMap (mMapManager-> getCurMapIndex () + 1, mMapManager-> getMapWidth ());}

Okay. Check the collision detection. The collision detection of box2d is maintained by the physical world. the physical world can know all collision events and handle them with a callback. We need to implement this callback b2ContactListener to handle collision detection by ourselves.

Let PlayScene inherit this class, implement a function BeginContact, and set a collision listener for world.

MWorld-> SetContactListener (this );

Let's take a look at the implementation of Collision Detection:

void PlayScene::BeginContact(b2Contact *contact){//    CCLog("begin contact!");        void* bodyUserDataA = contact->GetFixtureA()->GetBody()->GetUserData();    void* bodyUserDataB = contact->GetFixtureB()->GetBody()->GetUserData();        if (bodyUserDataA && bodyUserDataB)    {        B2Sprite* contactA = static_cast
 
  (bodyUserDataA);        BaseObject* obj = NULL;        if (contactA == mRunner->getRunnerSprite())        {            obj = static_cast
  
   (bodyUserDataB);        }else        {            obj = static_cast
   
    (bodyUserDataA);        }                if (COINTAG == obj->getObjSprite()->getTag()) {            ((Status*)(this->getParent()->getChildByTag(STATUSTAG)))->addCoin(1);            mRemoveObjs->addObject(obj);            SimpleAudioEngine::sharedEngine()->playEffect(pickUpCoins);        }else if(ROCKTAG == obj->getObjSprite()->getTag())        {            mRunner->die();            unscheduleUpdate();            mState = GameOverState;            GameOver* over = GameOver::create();            this->getParent()->addChild(over);        }            }}
   
  
 

After a collision occurs, the user data of the body is used for identification. This user data userData is a void * pointer that stores any user data. It is set when the physical genie is made to be used at this time.

The userData on the floor is NULL, so if this userData is not NULL, it is either a Runner or a gold coin or a rock. UserData of Runner is a B2Sprite, and userData of gold coins and rocks are sub-classes of BaseObject, So type conversion is performed. Use tags to differentiate gold coins and rocks. If it is a gold coin, add it to a CCArray and clear it in the update. If it is a rock, GameOver.

The distance between the score and the game cool is a separate CCLayer. Because PlayScene is an infinite Layer, the score should be displayed separately, otherwise it will run out of the screen. GameOver is a CCLayerColor, because a transparent layer indicates that the game is over.

I will not be able to see the figure. I will release the source code later.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.