cocos2dx3.0之跑酷使用磁鐵道具吸收金幣,cocos2dx3.0磁鐵
# cocos2dx3.0之跑酷使用磁鐵道具吸收金幣
轉載請註明[ http://blog.csdn.net/JANESTAR/article/details/45268851 ]
在跑酷遊戲中,我們常常需要有這麼一個情境,runner 在跑酷的過程中可以吃金幣,當他吃到一個磁鐵道具的時候,此時螢幕範圍內的所有金幣都會朝著runner 飛過來,達到吃金幣的效果。
原理
其實原理很簡單,我們在設計跑酷遊戲的過程中,其實runner的x座標一直沒有變化的,都是背景和道具在向後移動從而產生跑酷效果。當runner jump 的時候,其實是給runner 一個向上的初速度,讓他進行自由落體運動。cocos2dx3.0 整合了物理引擎chipmunk.我們可以很方便的擷取runner的動態座標。
獲得了runner的座標之後,我們就可以用一個簡單的action 來實現吸附金幣的效果了。具體情況是,只要金幣沒有移出道螢幕外,我們就可對金幣使用該action。
實現方法與關鍵代碼
下面我簡單的把實習方法和關鍵代碼闡述一下
auto contactListenner = EventListenerPhysicsContact::create(); contactListenner->onContactBegin = [this](PhysicsContact &contact) { auto b_1 = (Sprite* )contact.getShapeA()->getBody()->getNode(); auto b_2 = (Sprite* )contact.getShapeB()->getBody()->getNode(); //磁鐵吸收金幣 if(b_1->getTag() == magnetTag || b_2->getTag() == magnetTag){ b_1->setVisible(false); _baseManager->getCoinsByMagnet(_runner); } return false; }; Director::getInstance()->getEventDispatcher()-> addEventListenerWithSceneGraphPriority(contactListenner, this);}void BaseManager::getCoinsByMagnet(Runner* runner){ for(auto coin : _coinVec){ if(coin->getPositionX()>coin->getConSize().width/2){ Vec2 pos = runner->getPhysicsBody()->getPosition(); auto actionTo = MoveTo::create(0.6,pos); coin->runAction(actionTo); } }}
代碼應該很簡單,我就不解釋了。。。。