2013-02-13 103 views
-3

我試圖用EnchantJS製作一個HTML5/JavaScript遊戲,其中包含一個6x6的彩色方塊網格。我得到了1張圖片來顯示,而不是讓36x4行的代碼顯示我想將它全部移到一個函數中的所有圖像。代碼在第62行this.addChild(block);處中斷。我似乎無法弄清楚爲什麼這不起作用。我花了幾天的時間閱讀函數的功能,以及如何調用函數之間的信息。我無法弄清楚我做錯了什麼,我無法從搜索中找到答案。我來自一個純粹的Java和C++背景,所以我認爲我弄亂了語法並且不理解某些東西。Javascript OOP,函數

enchant(); 

window.onload = function() { 

    /* 
    * Game width and height. 
    * Note: Game scale is half so actual width=width/2 and 
    * actual heigh it height/2. 
    */ 
    var game = new Game(1280,768); 

    /* 
    * Game Preload Vars 
    */ 
    game.preload('res/bg2x.png', 
    'res/block.png'); 

    game.fps = 30; 
    game.scale = 0.5; 

    game.onload = function() { 

     console.log("Game Loaded"); 
     var scene = new SceneGame; 
     game.pushScene(scene); 

    } 

    game.start(); 
    window.scrollTo(0, 0); 

    var SceneGame = Class.create(Scene, { 

     initialize: function() { 

     var game, bg; 
     Scene.apply(this); 
     game = Game.instance; 

     // Background 
     bg = new Sprite(1280,768); 
     bg.image = game.assets['res/bg2x.png']; 

     // Populate Screen 
     this.addChild(bg); 

     gridBuilder(500,75); 

     } 

    }); 

    var gridBuilder = function(x,y) { 

     this.x=x; 
     this.y=y; 

     block = new Block; 
     block.x = x; 
     block.y = y; 
     this.block = block; 

     this.addChild(block); // THIS IS WHERE THE ERROR IS OCCURING. 

    }; 

    var Block = Class.create(Sprite, { 

     // The player character.  
     initialize: function() { 
     // 1 - Call superclass constructor 
     Sprite.apply(this,[100, 100]); 
     this.image = Game.instance.assets['res/block.png']; 
     // 2 - Animate 
     this.animationDuration = 0; 
     this.addEventListener(Event.ENTER_FRAME, this.updateAnimation); 
     }, 

     updateAnimation: function (evt) {   
      this.animationDuration += evt.elapsed * 0.001;  
      if (this.animationDuration >= 0.25) { 
       this.frame = (this.frame + 1) % 4; 
       this.animationDuration -= 0.25; 
      } 
     }, 

    }); 

} 
+5

「打破」如何?任何錯誤? – deceze 2013-02-13 15:20:21

回答

1

gridBuilder是一個函數,僅此而已。它沒有addChild方法。原因addChild工作在SceneGame是因爲SceneGame是由Class.create創建的,我假設它有一個固有的addChild方法。創建gridBuilder的方法與創建類SceneGame的方法相同,或者重新考慮您實際上想要gridBuilder執行的操作。無論如何,你正在做的事情並沒有加起來,你需要考慮你實際期望你的JS完成的事情。

+0

好吧,這很有意義。我來自Java/C++背景,因此我誤解了.js文件的結構。我通過從'gridBuilder'中取出this.addChild()'方法解決了我的問題,並且讓'gridBuilder'返回'block',然後將this.addChild(gridBuilder(500,75))'添加到SceneGame中。感謝您的解釋@EliGassert! – pattmorter 2013-02-13 15:42:23