Cocos2d-x中,在过渡场景异步加载图片和声音
2015-08-11 17:06
411 查看
游戏需要在过渡场景中完成对资源的加载。
对于图片的加载,可以使用TextureCache::addImageAsync或是TextureCache::addImage加载。
TextureCache::addImage为同步加载,其会在主线程中进行图片加载,这就有可能在加载时间比较长时,阻塞主线程。
TextureCache::addImageAsync为异步加载,其在加载时会创建新的线程用于加载图片。
所以在加载的图片很多时,需要使用异步加载。
示例代码如下,其中index是定义在头文件中的:
而loadingPicture函数通过switch可以控制每次调用回调函数所执行的动作。
对于图片的加载,可以使用TextureCache::addImageAsync或是TextureCache::addImage加载。
TextureCache::addImage为同步加载,其会在主线程中进行图片加载,这就有可能在加载时间比较长时,阻塞主线程。
TextureCache::addImageAsync为异步加载,其在加载时会创建新的线程用于加载图片。
所以在加载的图片很多时,需要使用异步加载。
示例代码如下,其中index是定义在头文件中的:
bool HelloWorld::init() { if (!Layer::init()) { return false; } index = 0; //定义在头文件中 // 图片1 Director::getInstance()->getTextureCache()->addImageAsync("picture1.png", CC_CALLBACK_1(HelloWorld::loadingPicture, this)); // 图片2 Director::getInstance()->getTextureCache()->addImageAsync("picture2.png", CC_CALLBACK_1(HelloWorld::loadingPicture, this)); // 图片3 Director::getInstance()->getTextureCache()->addImageAsync("picture3.png", CC_CALLBACK_1(HelloWorld::loadingPicture, this)); _loadingAudioThread = new std::thread(&HelloWorld::loadingAudio, this); return true; } void HelloWorld::loadingPicture(Texture2D * texture) { switch (index++) { case 0: SpriteFrameCache::getInstance()->addSpriteFramesWithFile("picture1.plist", texture); break; case 1: SpriteFrameCache::getInstance()->addSpriteFramesWithFile("picture2.plist", texture); break; case 2: SpriteFrameCache::getInstance()->addSpriteFramesWithFile("picture3.plist", texture); break; default: break; } } void HelloWorld::loadingAudio() { //初始化音乐 SimpleAudioEngine::getInstance()->preloadBackgroundMusic("music.wav"); //初始化音效 SimpleAudioEngine::getInstance()->preloadEffect("sound.wav"); }可以看到在init的函数中,加载完成png文件后,又新建了一个线程用来加载音乐。
而loadingPicture函数通过switch可以控制每次调用回调函数所执行的动作。
相关文章推荐
- c++ primer 第五版 笔记前言
- 那些年,我还在学习C# 学习笔记续
- Ruby 魔法 学习笔记之一
- sqlserver 数据库学习笔记
- CSS学习笔记Padding 属性中参数的定义与使用
- prototype 1.5 & scriptaculous 1.6.1 学习笔记
- prototype 学习笔记整理
- Oracle学习笔记(六)
- 关于SQLServer2005的学习笔记 XML的处理
- Jquery 基础学习笔记
- ExtJs 学习笔记基础篇 Ext组件的使用第1/2页
- linux Shell学习笔记第五天
- Jquery 学习笔记(二)
- Cocos2d-x中背景音乐和音效使用实例
- Cocos2d-x学习笔记之CCScene、CCLayer、CCSprite的默认坐标和默认锚点实验
- Cocos2d-x UI开发之CCControlPotentiometer控件类使用实例
- Cocos2d-x UI开发之文本类使用实例
- Cocos2d-x保存用户游戏数据之XML文件是否存在问题判断方法
- Cocos2d-x UI开发之菜单类使用实例
- Cocos2d-x UI开发之CCControlButton控件类实例