您的位置:首页 > 移动开发 > Cocos引擎

【cocos2dx学习笔记】制作Loding场景

2014-11-22 23:53 190 查看
为什么要制作loading场景?

在实际游戏中会有一个场景中拥有大量的资源,直接跳转会造成卡顿,而且在场景跳转的过程中会存在一个时间段,在这个时间段中跳转前的场景和将要跳转到的场景都占用着系统资源,会使系统更加卡。

制作loading场景的两种方法:

1、伪loading跳转:

制作一个只拥有背景和进度条的场景夹在两个场景的中间作为缓冲,自己设定时间使得场景进行两次跳转。

2、真loading跳转

利用此函数

CCTextureCache::sharedTextureCache()->addImageAsync("HelloWorld.png", this, callfuncO_selector(MyScene::loadingcallback));
进行预加载图片资源

具体代码如下

loading场景MyScene的头文件:

#include "cocos2d.h"
class MyScene:public cocos2d::CCLayer
{
public:
MyScene();
~MyScene();
virtual bool init();
static cocos2d::CCScene* scene();
void menuCallBack(CCObject *sender);
//void funcCallBack();
void turntoscene(); //转换场景
void loadingcallback(cocos2d::CCObject* sender); //加载每个资源的回调函数
private:
cocos2d::CCLabelTTF* plable1; //loading....字样
cocos2d::CCLabelTTF* plable2; // 百分号
float numberofSprites; // 需要预加载的资源数量
float numberoflodedSprites; // 已经预加载好的资源数量
cocos2d::CCProgressTimer* loadprogess; //进度条
CREATE_FUNC(MyScene);
};
MyScene源文件中的init函数

bool MyScene::init()
{
CCSize size = CCDirector::sharedDirector()->getWinSize();
plable1 = CCLabelTTF::create("Loding.......", "Arial", 20);
plable2 = CCLabelTTF::create("0%", "Arial", 20);
plable1->setPosition(ccp(size.width*0.4,size.height*0.4));
plable2->setPosition(ccp(size.width*0.57, size.height*0.4));
addChild(plable1);
addChild(plable2);
numberofSprites = 200;
numberoflodedSprites = 0;

//CCSprite* loadbg = CCSprite::create(""); //进度条底图
//loadbg->setPosition(ccp(size.width / 2, size.height*0.3));
//addChild(loadbg);

//创建进度条

loadprogess = CCProgressTimer::create(CCSprite::create("btn-about-selected.png"));

loadprogess->setBarChangeRate(ccp(1, 0)); //进度条变化速率
loadprogess->setType(kCCProgressTimerTypeBar); //进度条类型
loadprogess->setMidpoint(ccp(0,1)); // 设置进度条变化方向
loadprogess->setPosition(ccp(size.width / 2, size.height*0.3));
loadprogess->setPercentage(0); //设置初始值
addChild(loadprogess, 1);

//加载资源
for (int i = 0; i < 100; i++)
{
CCTextureCache::sharedTextureCache()->addImageAsync("HelloWorld.png", this, callfuncO_selector(MyScene::loadingcallback));
CCTextureCache::sharedTextureCache()->addImageAsync("Icon.png", this, callfuncO_selector(MyScene::loadingcallback));
}
return true;
}MyScene源文件的loadingcallback函数
void MyScene::loadingcallback(cocos2d::CCObject* sender)
{
numberoflodedSprites++;
char a[10];
float values = (numberoflodedSprites / numberofSprites) * 100;
sprintf(a, "%d%%", (int)values);
CCLOG("callback");
plable2->setString(a);
loadprogess->setPercentage(values);
if (numberoflodedSprites == numberofSprites)
turntoscene();
}MyScene源文件的场景转换函数
void MyScene::turntoscene()
{
CCDirector::sharedDirector()->replaceScene(HelloWorld::scene());
}效果图如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cocos2dx 游戏