Cocos2d 与 browserify: cc.Layer 未定义

Cocos2d with browserify: cc.Layer is undefined

我正在尝试使用 Javascript 开始使用 Cocos2d,但我想从 ES6 编译并使用 Browserify 管理我的依赖项。所以我将编译后的 javascript 作为 main.js.

输出到我的 Cocos2d 项目目录

当我尝试 运行 项目时,出现此错误:

Uncaught TypeError: Cannot read property 'extend' of undefined

在这一行:

var HelloWorldLayer = cc.Layer.extend({

当我 运行 没有 ES6/browserify 的软件时,这并没有发生,但我不确定为什么 cc 变量会有所不同(它已定义,但没有图层 属性)。我也试过将其放在该行上方:const cc = window.cc,但这也不能解决问题。

如果有人能解释这里发生了什么或如何解决它,我将不胜感激。

如果需要,我可以 post 更多代码(它几乎与基本的 hello world 应用程序相同)或我的 gulpfile 任务。

我能够通过将 CocosJS 的 main.js 排除在 Browserify 构建之外并使用它通过公开函数 window.startApp 将正确的 cc 传递到编译的应用程序来解决问题:

main.js(未编译)

cc.game.onStart = function(){
    if(!cc.sys.isNative && document.getElementById("cocosLoading")) //If referenced loading.js, please remove it
        document.body.removeChild(document.getElementById("cocosLoading"));

    window.startApp(cc);
};
cc.game.run();

app.js(用Browserify/Babelify编译)

import "babel-core/polyfill";
import {values} from "lodash";
import HelloWorldScene from "hello-world-scene";
import res from "resources";

window.startApp = (cc) => {
        // Pass true to enable retina display, disabled by default to improve performance
    cc.view.enableRetina(false);
    // Adjust viewport meta
    cc.view.adjustViewPort(true);
    // Setup the resolution policy and design resolution size
    cc.view.setDesignResolutionSize(800, 450, cc.ResolutionPolicy.SHOW_ALL);
    // The game will be resized when browser size change
    cc.view.resizeWithBrowserSize(true);
    //load resources
    cc.LoaderScene.preload(values(res), () => {
        cc.director.runScene(new HelloWorldScene());
    });
};

我仍然不确定为什么编译 main.js 会导致 cc 缺少基本属性。我认为这可能与 Browserify 将编译后的代码包装在严格模式函数中有关,但我无法禁用严格模式以找出答案。

如果有人感兴趣,我用我的解决方案创建了一个 github 回购协议:

https://github.com/FullR/cocos-es6-browserify

我刚 运行 遇到了同样的问题。似乎 类 像 cc.Layer 只能在调用 cc.game.run() 后可用。

因此您必须确保在执行其余代码之前调用 cc.game.run()