原理,使用
CCTextureCache::sharedTextureCache()->addImageAsync("background.png", this, callfuncO_selector(Assets::loadingCallBack));
載入紋理時,每載入一張紋理調用一次Assets::loadingCallBack,Assets::loadingCallBack實現進度條的進度跟進和判斷跳轉
步驟:
1.建立一個Cocos2d-x工程,保證能成功運行(我一直在說廢話,呵呵)
2.在HelloWorldScene.h檔案中修改和增加代碼
3.在HelloWorldScene.cpp檔案中修改和增加代碼
4.建立SecondScene.h和SecondScene.cpp兩個檔案,用於載入完成後跳轉
1.建立一個Cocos2d-x工程,保證能成功運行,沒有其他的了
2.在HelloWorldScene.h檔案中修改和增加代碼
HelloWorld(); virtual bool init(); static cocos2d::CCScene* scene(); CREATE_FUNC(Assets);void loadingCallBack(cocos2d::CCObject *obj);//回呼函數,每載入一張紋理就調用一次private:cocos2d::CCLabelTTF *m_pLabelLoading;//文字標籤,用於顯示“Loading”字樣cocos2d::CCLabelTTF *m_pLabelPercent;//文字標籤,用於顯示百分比int currentNum;//當前載入到第幾張int totalNum;//載入總數
3.在HelloWorldScene.cpp檔案中修改和增加代碼
建構函式,初始化currentNum和totalNum
HelloWorld::HelloWorld():currentNum(0),totalNum(500){}
修改init()中的do代碼塊為:
CC_BREAK_IF(! CCLayer::init());//取得螢幕大小CCSize size = CCDirector::sharedDirector()->getWinSize();//文字標籤,用於顯示Loding字樣和載入的進度m_pLabelLoading = CCLabelTTF::create("Loading...", "Arial", 25);m_pLabelPercent = CCLabelTTF::create("0%", "Arial", 25) ;m_pLabelLoading->setPosition(ccp(size.width / 2, size.height / 2 + 50));m_pLabelPercent->setPosition(ccp(size.width / 2, size.height / 2));this->addChild(m_pLabelLoading);this->addChild(m_pLabelPercent);//載入HelloWorld.png紋理for (int i = 0; i < 500; i++){//載入紋理,回調Assets::loadingCallBackCCTextureCache::sharedTextureCache()->addImageAsync("HelloWorld.png", this, callfuncO_selector(Assets::loadingCallBack));} bRet = true;
回呼函數loadingCallBack的實現:
void Assets::loadingCallBack(cocos2d::CCObject *obj){//currentNum初始值為0,每載入一張紋理值自加1++currentNum;char tmp[10];//求得百分比sprintf(tmp, "%d%%", (int)(((float)currentNum / totalNum) * 100));//設定標籤顯示的內容m_pLabelPercent->setString(tmp);//如果當前載入的張數跟總數相等則進行情境跳轉if (currentNum == totalNum){this->removeChild(m_pLabelPercent, true);this->removeChild(m_pLabelLoading, true);//情境跳轉CCScene *m_SecondScene = SecondScene::scene(); CCDirector::sharedDirector()->replaceScene(CCTransitionJumpZoom::create(1.0f,m_SecondScene));}}
4.建立SecondScene.h和SecondScene.cpp兩個檔案,用於載入完成後跳轉
建立情境的步驟詳見http://blog.csdn.net/zlqqhs/article/details/9245125
將SecondScene.cpp檔案下的init函數下的代碼改為:
//通過名字從CCTextureCache中取得紋理CCTexture2D *texture = CCTextureCache::sharedTextureCache()->textureForKey("HelloWorld.png");//執行個體化精靈CCSprite *m_sprite = CCSprite::createWithTexture(texture);CC_BREAK_IF(!m_sprite);//設定精靈位置m_sprite->setPosition(ccp(100, 100));//添加精靈到情境this->addChild(m_sprite);bRet = true;