如何自定义 Cocos2d-html5 Loading 界面

2025-04-22 12:03:34
推荐回答(2个)
回答1:

在使用 C++ 编写

游戏的时候,通常在运行游戏之前,需要加载游戏资源,这样是为了让游戏在运行时更为流畅,避免了在运行时加载资源,而出现卡顿现象,影响用户体验,因为加
载资源是非常耗时、耗资源的操作。在 Cocos2d-html5
中也是同样,在运行游戏之前,预先加载好所有的资源(加载到
),以保证游戏的流畅运行。

Cocos2d-html5 的加载流程

在开始我们的替换工作之前,大致说一下必要的(只注重我们在乎的细节问题)原有的加载流程,以**HelloHTML5World**为例 。从其主页面 index.html开始,我们需要了解三个文件的运作方式,index.html、cocos2d.js 和 main.js:

浏览器首先加载 index.html 页面,值得注意的有两点,在页面的 DOM 树中,能看到命名为**gamecanvas**的**Canvas**元素,它将会是游戏的画布,另一点,在页面的最后,加载了 cocos2d.js 文件。

cocos2d.js 内中,定义了程序运行需要的一些参数,如 显示 FPS,是否加载扩展库,物理引擎库等,其中 engineDir 设置了引擎所在的位置,appFiles 设置了,当前项目所用到需要加载的 js 程序代码。并定义了当 DOM 加载完成时运行的代码(你可以在 【这里】 查看所有代码。):
window.addEventListener('DOMContentLoaded', function () {
// 添加脚本
var s = d.createElement('script');
// 这里判断了是否使用自定义的 单文件作为库加载,对库的优化压缩文件
if (c.SingleEngineFile && !c.engineDir) {
s.src = c.SingleEngineFile;
}
else if (c.engineDir && !c.SingleEngineFile) {

s.src = c.engineDir + 'platform/jsloader.js';
}
else {
alert('You must specify either the single engine file OR the engine directory in "cocos2d.js"');
}

回答2:

自定义Cocos2d-html 5 Loading界面代码:

// 这里定义了 Logo 图片的 Base64 编码,至于为什么,后面将会说明,这里的编码内容挺多,固做简写
logoData = "data:image/png;base64,...";

Loading = cc.Scene.extend(
_logo: null,
_logoTexture: null,
_texture2d: null,
_bgLayer: null,
_label: null,
_winSize:null,
_processLayer: null, // 相比 LoaderScene 的实现,添加了两个属性,标示进度条层和进度条长度
_processLayerLength: null,

// 构造函数
ctor: function () {
this._super();
this._winSize = cc.Director.getInstance().getWinSize();
},
init:function(){
cc.Scene.prototype.init.call(this);

// logo 图片和 label 的添加 .. 这里省略,于 LoaderScene 同样

// 设置进度条层,它就是一个红色颜色层,通过长度来标示加载的进度
this._processLayerLength = 500;
this._processLayer = cc.LayerColor.create(cc.c4b(255, 100, 100, 128), 1, 30);
this._processLayer.setPosition(cc.pAdd(centerPos, cc.p(- this._processLayerLength / 2, -logoHeight / 2 - 50)));
// 可以启用锚点,并设置以满足自己的需要
// this._processLayer.ignoreAnchorPointForPosition(false);
// this._processLayer.setAnchorPoint(cc.p(0, 0));

this._bgLayer.addChild(this._processLayer);
},
// 以下方法的实现并没有跟 LoaderScene 有什么不同
// _initStage: ...
// onEnter ...
// onExit ...
// initWithResources ...
// _startLoading ...
// _logoFadeIn
// 每帧更新
_updatePercent: function () {
var percent = cc.Loader.getInstance().getPercentage();
var tmpStr = "Loading... " + percent + "%";
this._label.setString(tmpStr);

// 设置当前进度条层的长度
this._processLayer.changeWidth(this._processLayerLength * percent / 100);

if (percent >= 100)
this.unschedule(this._updatePercent);
}
});
// 这里于 LoaderScene 的实现同样
Loading.preload = function (resources, selector, target) {
if (!this._instance) {
// 创建一个 Loading
this._instance = new Loading();
this._instance.init();
}
// ...
return this._instance;
};