您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
三六零分类信息网 > 三明分类信息网,免费分类信息发布

HTML5 游戏开发 之 资源加载篇(2)

2025/10/11 10:07:11发布19次查看
四) 下载过程的管理
4.1) 如何管理成千上百的资源
在游戏开发的过程中,很有可能会有成千上百张图片。最直接的方式,是将这些图片编写在代码中,但是图片的名字很容易改变的,会造成大量的维护工作,甚至影响代码的打包和发布。我的同事boris,在他的代码演示库中,给出了一个参考实现方式,如下。这种方式,可以保证,在需要修改或者调整资源名称或者路径的时候,不需要接触代码。
{
  assetroot: url/to/assets,
  bundles: [
  {
        name: unique bundle name,
        contents: [
        relative/path/to/asset.jpg,
        another/asset.mp3
          ]
  },
  autodownload: true
}
var gal = new gameassetloader(http://path.to/gal.manifest);
// load the gal. if manifest indicates autodownload, this call will
// start loading assets one by one.
gal.init(function() {
// called when the library is initialized
});
复制代码
更完整的代码,可以参考github上的源代码
4.2) 如何实现批处理的下载
再获得了资源列表之后,就要开始资源的下载。显然,需要这样的方法。
assetmanager.prototype.downloadall = function(downloadcallback) {
  for (var i = 0; i   var path = this.downloadqueue[i];
  var img = new image();
  var that = this;
  img.addeventlistener(load, function() {
        // coming soon
  }, false);
  img.addeventlistener(error, function() {
  // coming soon
  }, false);
  img.src = path;
}
}

下载的过程中,一般情况下都需要一个进度条,来显示完成的情况,所以必须对assetmanager进行计数。

function assetmanager() {
  this.successcount = 0;
  this.errorcount = 0;
  this.downloadqueue = [];
}
assetmanager.prototype.isdone = function() {
  return (this.downloadqueue.length == this.successcount + this.errorcount);
}
assetmanager.prototype.getprocess = function() {
  return (this.successcount + this.errorcount)/this.downloadqueue.length;
}
复制代码
显然,也需要对每个img的load和error事件,进行计数。还请注意downloadall函数有个参数叫做downloadcallback,在资源下载完成以后,通知此函数,进入游戏过程中。
img.addeventlistener(load, function() {
  that.successcount += 1;
  if (that.isdone()) {
        downloadcallback();
  }
}, false);
img.addeventlistener(error, function() {
  that.errorcount += 1;
  if (that.isdone()) {
        downloadcallback();
  }
}, false
复制代码
4.3) 游戏中的不同关卡
游戏通常是分关卡的,完全没有必要在一开始就将游戏的所有资源下载到本地,毕竟不是每个玩家都会将游戏通关。为了按需下载,比较完备的资源加载器,应该可以对每个资源配上一个标签或者属性,可以标志它属于哪一关。每一关的开始,只下载和本关相关联的资源,在每一关结束的时候,在去下载下一关的资源。不仅减少用户的不必要的等待时间,还可以有效的减少服务器的压力。
5.资源加载器的具体实现
5.1 preloadjs
官方网站:http://www.createjs.com/#!/preloadjs/download
开源代码:https://github.com/createjs/preloadjs/
专门用于资源下载的类库,非常好用,考虑的也非常全面,首先推荐的一款软件,尤其是读者不希望加载特别大的游戏引擎是,这款软件可以作为首选。
具体的例子可以参考:https://github.com/createjs/preloadjs/tree/master/examples
(未完待续)
三明分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product