該部落格為原創部落格,轉載請保留原始位址:http://blog.csdn.net/kantian_/article/details/21184609
遊戲中什麼最占用記憶體,毋庸置疑絕對是紋理,用mac開發的同學如果有潔癖一定用過Xcode自帶的記憶體分析工具,你可以發現大部分記憶體裡面存的都是紋理(簡單了解就是圖檔啦)。如果為了減少記憶體使用而增加加載次數勢必會令遊戲不流暢,如果一次性加載很多紋理又會消耗掉更多記憶體,是以記憶體的載入時間和量都是非常值得研究的一個事情。限于筆者水準限制以及該遊戲的簡單性,這裡其實隻是冰山一角。回到這個遊戲,該遊戲所用到的素材不多,一張1024x1024的大圖可以容納下所有的素材還有的多,是以這裡我們可以在遊戲一開始全部載入。
載入的資源包括圖檔素材的載入和音樂素材的載入。圖檔的載入一定是一個異步操作,cocos2dx本身就提供了一個異步載入紋理的接口:
// start ansyc method load the atlas.png
Director::getInstance()->getTextureCache()->addImageAsync("atlas.png",CC_CALLBACK_1(LoadingScene::loadingCallBack,this));
TextureCache這個類裡面的addImageAsync的方法便是一個異步加載圖檔紋理的方法,第一個參數是圖檔的名字(你放在Resource裡面的圖檔),第二個參數便是圖檔異步加載完成之後需要調用的回調函數,回調函數包含了加載完成之後的紋理對象。
addImageAsync:
/* Returns a Texture2D object given a file image
* If the file image was notpreviously loaded, it will create a new Texture2D object and it will return it.
* Otherwise it will load atexture in a new thread, and when the image is loaded, the callback will becalled with the Texture2D as a parameter.
* The callback will be calledfrom the main thread, so it is safe to create any cocos2d object from thecallback.
* Supported image extensions:.png, .jpg
* @since v0.8
*/
virtualvoidaddImageAsync(conststd::string&filepath,std::function<void(Texture2D*)>callback);
回調函數:
voidLoadingScene::loadingCallBack(Texture2D*texture){
AtlasLoader::getInstance()->loadAtlas("atlas.txt",texture);
// After loading the texture ,preload all the sound
SimpleAudioEngine::getInstance()->preloadEffect("sfx_die.ogg");
SimpleAudioEngine::getInstance()->preloadEffect("sfx_hit.ogg");
SimpleAudioEngine::getInstance()->preloadEffect("sfx_point.ogg");
SimpleAudioEngine::getInstance()->preloadEffect("sfx_swooshing.ogg");
SimpleAudioEngine::getInstance()->preloadEffect("sfx_wing.ogg");
// After load all the things, changethe scene to new one
//auto scene =HelloWorld::createScene();
autoscene=WelcomeScene::create();
TransitionScene*transition=TransitionFade::create(1,scene);
Director::getInstance()->replaceScene(transition);
}
紋理載入完成之後我們就需要用紋理來形成精靈來緩存起來友善以後使用,因為來自原版遊戲的素材并不是用plist來打包精靈的,是以這裡就用不了SpriteFrameCache類提供的接口來對打包的紋理進行處理,是以這裡我仿照SpriteFrameCache類寫了一個AtlasLoader來對打包完成紋理進行解析,關于這個類,第一節已經講過了。完成了圖檔紋理的載入接下來就需要對遊戲音效就行預載入,不過可惜的是cocos2dx并咩有提供音效檔案的異步載入方法,不過該遊戲中用到的音效都很小,而且載入界面的顯示的也是一張靜态圖,是以這裡就算阻塞了主線程也沒有太大關系,是以這裡就直接載入了。如果你的遊戲中需要載入大量的很大的音樂檔案,那麼可能就需要你自己寫一個異步載入的方法了,官方有一個多線程的解決方案,需要的同學可以參考下官網,不過這裡應該是平台強相關的。最後全部都完成之後就隻需要跳轉的接下去的場景便完成了遊戲素材的加載。之後取精靈隻需要擷取AtlasLoader的單例實體便可以擷取精靈了
auto sprite = AtlasLoader::getInstance()->getSpriteFrameByName(“spritename”)
具體代碼以及遊戲截屏還有遊戲請移步該遊戲在代碼倉庫:http://oiteboys.github.io/Earlybird/