[英]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
變量為什么會有所不同(已定義,但沒有Layer屬性)。 我還嘗試將其放置在該行上方: const cc = window.cc
,但這也不能解決問題。
如果有人能解釋這里發生了什么或如何解決,我將不勝感激。
如果需要,我可以發布更多代碼(與基本的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存儲庫:
我只是遇到了同樣的問題。 似乎cc.Layer
類的類僅在調用cc.game.run()
之后才可用。
因此,您必須確保在執行其余代碼之前調用cc.game.run()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.