cocos2D-javascript 入门分享

这篇文章先是用中文写的,因为要给老外分享,我又翻译成英文了。(欢迎转载~~~)


cocos2D-javascript使用了jah来管理js文件和资源文件。但是网站上的文档和教程都没有提到如何使用它。一番深入挖掘源代码后,我来分享一下成果。

‘jah’ is the library used by cocos2D-javascript for managing js files and asserts file. But there are not any materials mentioned jah from the document and tutorial in the site. The origin description from the author's github is:

"Jah is simple Node.js framework which enables you to build Web browser based applications using theCommonJS module system. This means you can easily break your application up into separate directories and files and include them when needed using the require function."

After digging deep in the src code, I want to share you the result.

init.js:

(function (window) {

    var assetURL = STATIC_URL + "assets";
    var scripts = [
      "http://code.jquery.com/jquery-1.10.2.min.js",
      STATIC_URL + "js/lib/cocos2d.js",
      STATIC_URL + "js/src/main.js",
      STATIC_URL + "js/src/state_machine.js",
      STATIC_URL + "js/src/logic_controller.js",
      STATIC_URL + "js/src/html_ui.js",
      STATIC_URL + "js/src/menu_scene.js",
      STATIC_URL + "js/src/loading_scene.js",
      STATIC_URL + "js/src/game_scene.js",
      STATIC_URL + "js/src/win_scene.js",
      ];
    var assets = [
      {baseUri:assetURL, path:"/questions/whois_that_pokemon.jpg", mimeType:"image/jpg"},
      ];
    
    window.__jah__ = {resources:{}, assetURL: assetURL, __blockReady: true};

    function initializeApplication () {
        if (window.document.readyState != 'complete') return;
        var i = 0
        function nextScript () {
            if (scripts.length > i) {
                addScript(document, scripts[i], nextScript)
                i++
            } else {
                window.__jah__.__triggerReady()
            }
        }
        nextScript();
        
        for(i = 0; i < assets.length; ++i) {
        	var asset = assets[i];
        	addAsset(asset.baseUri, asset.path, asset.mimeType);
        }
    }

    function addScript (document, script, callback) {
        s = document.createElement('script')
        s.type = 'text/javascript'
        s.defer = true
        s.onload = callback
        s.src = script
        document.body.appendChild(s)
    }

    function addAsset(baseUri, path, mimeType) {
    	__jah__.resources[path] = {data: baseUri + path, mimetype: mimeType, remote: true};
    }

    if (typeof window.document.onreadystatechange !== 'undefined') {
        var listener = window.document.addEventListener('readystatechange', initializeApplication, false)
        initializeApplication()
    } else if (window.document.readyState) {
        var checkReadyState = function () {
            if (window.document.readyState == 'complete') {
                initializeApplication()
            } else {
                setTimeout(checkReadyState, 13)
            }
        }
        checkReadyState()
    } else {
        window.onload = initializeApplication
    }
})(window)

作者提供了一套帮助加载模块和资源的模板js,并提供了一套nodejs脚本来帮助build出模块和资源。以上代码是我实例出的代码,并进行过些许改动,不影响作者原意。

Init.js is an template file for initializing module and assert. The above code is an instance with some mine changes to illustrate the principle.

.

这里首先要明确“模块”和“资源”的概念。

Firstly we should define the terms : "module" and "asset".


“模块”是指经过编译的单独的js文件。这里的编译仅仅是一些文法上的包装。可以通过require全局函数来导出模块所暴露的对象,供模块间使用。

"module" refers to the separated js files which have been built. The build here is just some kind of grammar wrapping. The globe function 'require' can be used to export the object which the module wants to expose for external using.


“资源”是指mimeType类型的资源,可以是js脚本,图片文件,视频文件,txt,json文本等……可以通过resource全局函数来引用。目前jah只支持一些文本类型的资源和图片资源。

‘asset’ refers to mime type resources. It can be js script, image, video, txt, json and so on... The globe function 'resource' can be used to reference the wanted asset. For now jah only implements some text type asset and image.


"模块"和“资源”都定义在全了__jah__这个全局变量中的resource对象里了。每一项都是resource中的一个属性对象,通过path作为属性名来查找具体的对象。remote属性表示它是一个“资源”,对于“模块”它的值是false。对“模块”来说,data是一个闭包对象来供程序调用。对“资源”来说,data保存url。

'module' and 'asset' are both listed in the 'resource' object which belongs to the globe object __jah__. The path is as the property name for the key to reference the resource. The 'remote' property means the resource will be loaded as an 'asset'. So the 'module' will has a false value. For 'module', data stands for a closure object for other scripts using. For 'asset', data stands for the url.

window.__jah__.resources[path] = {data: string/closure, mimetype: string, remote: bool};

从init.js内容来看,只看到了addAsset函数添加里__jah__.resource的属性,addScript没有。那是因为remote为false的“module”只能被直接append到dom中去,而“assert”可以被__jah__来动态的加载。

From init.js, we can see only addAsset function adds property to __jah__.resource, addScript not. It is because "module" resource which has a false value on remote property won't be loaded by jah( jah is the one of "modules", it can't be loaded by itself ), but "asset' resource can be loaded by jah dynamiclly.


所以要想利用模块化的特性,部署的js文件必须经过“编译”。以下是一个“模块”文件的例子,你可以看到所谓的“编译”只是加了一个resources属性的封装而已。

To take advantage of the modularization feature, the js must be "built". You can find that the so-called 'build' is just a property wrap in __jah__.resources though the following sample.

__jah__.resources["/main.js"] = {data: function (exports, require, module, __filename, __dirname) {"use strict"  // Use strict JavaScript mode

var events = require('events');
var director = require('cocos2d').Director.sharedDirector;
var logic_controller = require('/logic_controller').logic_controller;

function main() {
	events.addListener(director, 'ready', function (director) {
		logic_controller.Init();
	})
	director.attachInView(document.getElementById('view'));
	director.runPreloadScene();
	
	var img = resource('/questions/whois_that_pokemon.jpg');
}


exports.main = main;
}, mimetype: "application/javascript", remote: false};


接下来事情就比较容易了。初始化了“模块”和“资源”列表后,就到了真正的加载逻辑。Dom加载完所有脚本后,__jah__的内部功能在加载成功cocos2d.js后被初始化完成。之后require,resource什么的就都能用了。注意到__triggerReady()函数了吧,之后的逻辑会显示cocos2D-javascript的一个预置的资源加载场景,该场景里会启动一个preloader,来加载“资源”列表中的东西。加载的过程中场景中会伴随进度条显示,以提供一个良好的用户体验。当然你可以重载这个加载场景,以达到你想要的效果。

The following logic begins to be simple. After initialize the array of 'module' and 'asset', the DOM will complete all the appended scripts. One of them must be cocos2d.js. It will init __jah__ inside function. Then 'require' and 'resource' will be added as globe functions. Do you have an attention on  '__triggerReady' ? It will drive to run a  preload scene preseted by cocos2D-javascript. In this scene a preloader will be started for loading the asserts in the list one by one. While the process, user can see the process in the process bar of the scene. Of course,  you can overload the preload scene to change the representation by what you want.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Cocos2d-JS开发之旅 从HTML 5到原生手机游戏》 《Cocos2d-JS开发之旅——从HTML 5到原生手机游戏》从简单到复杂逐渐深入介绍Cocos2d-JS,包括HTML5和手机原生游戏两个方面的内容。这些内容融汇了作者多年的工作经验和Cocos2d-JS 的亲身使用教训,有助于读者快速掌握游戏开发的方法和避开不必要的麻烦。 《Cocos2d-JS开发之旅——从HTML 5到原生手机游戏》以两个游戏为线索,每一章的学习都为最终实现游戏而准备。除了基础的Cocos2d-JS使用方法,本书还会探讨如何调试发布原生手机游戏和另外一些高级话题。 《Cocos2d-JS开发之旅——从HTML 5到原生手机游戏》适合所有对2D 游戏开发感兴趣的人群,尤其是计算机专业学生、Flash/JS 开发者,因为Cocos2d-JS简单易懂,读者会发现自己已有的基础能快速应用或转移到Cocos2d-JS 游戏的开发中。 目录 第一部分 准 备 篇 第1 章 Cocos2d-JS 介绍 / 2 第2 章 跑起我们的HelloWorld / 10 第一部分总结 / 27 第二部分 做一个简单的小游戏 第3 章 Cocos2d-JS 的平面世界 / 30 第4 章 让世界来点动静 / 51 第5 章 让玩家操纵这个世界 / 72 第6 章 控制小怪按时出现——定时器 / 84 第7 章 游戏界面 / 96 第8 章 不能光说不练——小小碰碰糖 / 122 第9 章 把成果分享到网上 / 143 第二部分总结 / 158 第三部分 再做一个高大上游戏 第10 章 走向高大上的必经之路——简单的性能优化 / 160 第11 章 让主角不再死板 / 173 第12 章 动态的背景 / 188 第13 章 界面的文字有点丑 / 204 第14 章 超炫的效果——粒子系统 / 211 第15 章 尝试做一个更大的游戏——Hungry Hero(上篇)/ 226 第16 章 尝试做一个更大的游戏——Hungry Hero(下篇)/ 235 第三部分总结 / 291 第四部分 把两个游戏做成原生手机游戏 第17 章 咱们也来做APP / 294 第18 章 真是这么美好吗?更多问题来了 / 304 第四部分总结 / 320 第五部分 高 级 篇 第19 章 订阅者模式——事件机制 / 322 第20 章 屏幕尺寸适配哪家强 / 331 第21 章 让死去的主角灰掉——渲染控制 / 342 第22 章 动态热更新 / 363 第23 章 想说的还有很多 / 374 第五部分总结 / 376

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值