Cocos2d with browserify: cc.Layer is undefined

Cocos2d with browserify: cc.Layer is undefined

本文关键字:Layer is undefined cc with browserify Cocos2d      更新时间:2023-09-26

我正在尝试使用Javascript开始使用Cocos2d,但我想从ES6编译并使用Browserify管理我的依赖项。所以我输出我的编译javascript到我的Cocos2d项目目录main.js.

当我尝试运行项目时,我得到这个错误:

Uncaught TypeError: Cannot read property 'extend' of undefined

在这一行:

var HelloWorldLayer = cc.Layer.extend({

当我在没有ES6/browserify的情况下运行软件时,这种情况不会发生,但我不确定为什么cc变量会有任何不同(它是定义的,但没有Layer属性)。我也试过把这个放在那行上面:const cc = window.cc,但这也不能解决这个问题。

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

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

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

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

我能够通过将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 repo与我的解决方案,如果有人感兴趣:

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