Cocos2d-x中,在过渡场景异步加载图片和声音

游戏需要在过渡场景中完成对资源的加载。

对于图片的加载,可以使用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可以控制每次调用回调函数所执行的动作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值