【问题标题】:Javascript OOP, functions [closed]Javascript OOP,函数[关闭]
【发布时间】:2013-01-29 04:33:31
【问题描述】:

我正在尝试使用 EnchantJS 制作一个 HTML5/JavaScript 游戏,其中包含一个 6x6 的彩色方块网格。我有 1 张图像要显示,但不是有 36x4 行代码来显示我想将其全部移动到函数中的所有图像。代码在第 62 行中断this.addChild(block);。我似乎无法弄清楚为什么这不起作用。过去几天我一直在阅读什么是函数以及如何在函数之间调用信息。我无法弄清楚自己做错了什么,也无法通过搜索找到答案。我来自纯 Java 和 C++ 背景,所以我认为我搞砸了语法并且不理解某些东西。

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;
          }
        },

    });

}

【问题讨论】:

  • “中断”如何?有什么错误吗?

标签: javascript oop function addchild


【解决方案1】:

gridBuilder 是一个函数,仅此而已。它没有addChild 方法。 addChildSceneGame 中起作用的原因是因为SceneGame 是由Class.create 创建的,我假设它固有地具有addChild 方法。要么创建 gridBuilder,就像创建类 SceneGame 一样,要么重新考虑你真正想要 gridBuilder 做什么。无论哪种方式,您所做的事情并没有加起来,您需要考虑您实际上期望您的 JS 完成什么。

【讨论】:

  • 好吧,这很有意义。我来自 Java/C++ 背景,所以我误解了 .js 文件的结构。我通过将this.addChild() 方法从gridBuilder 中取出并让gridBuilder 返回block 然后将this.addChild(gridBuilder(500,75)) 添加到SceneGame 中来解决了我的问题。感谢@EliGassert 的解释!
猜你喜欢
  • 1970-01-01
  • 2020-03-27
  • 2011-04-14
  • 2015-12-04
  • 2016-08-17
  • 1970-01-01
  • 2022-06-13
  • 2021-11-24
  • 2022-07-06
相关资源
最近更新 更多