2013-02-13 71 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