javascript游戏我应该如何减少实体与主窗口的耦合?

时间:2012-04-23 20:21:06

标签: javascript

我在游戏中有一个实体,它有一个更新方法,它需要定位最近的僵尸,目前僵尸列表只是我访问的全局对象,但这似乎是错误的,我可以将列表传递给更新方法,但我不确定这是否是最好的方法?

这是我的更新方法的简化版本:

this.update = function () {
                var targetedZombie = null;
                //TODO: should not be using the zombies object - tight coupling should be removed
                var alivezombies = [];
                for (var zombie in zombies) {
                    if (zombies[zombie].Alive) {
                        alivezombies.push(zombies[zombie]);
                    }
                }

                targetedZombie = this.GetClosestEntity(alivezombies);
                if (targetedZombie) {
                    Fire(this, targetedZombie);
                }
});

2 个答案:

答案 0 :(得分:1)

使用闭包 //初始你的api

    (function(global) {
      var zombies = []; // accessible only to you

      function zombieManager() { 
         this.addZombie = function() {  zombies.push() }
         this.killHalfZombies = function() { 
                  zombies = zombies.filter(function(item,i) { return i % 2 == 0});
         }
      }
      global.zombieManager = new zombieManager();

      function hero() {

      };

      hero.prototype.update = function() {
        //dig zombies[]
        //do whatever state change
      };
      global.hero = hero;
    })(window); //<-- you pass in whatever rootlevel object we have. window in a browser.

//use api
    var myhero = new hero();
    hero.update() //<-- this can access zombies

    zombieManager.addZombie(); //<-- zombieManager is a singleton and is responsible for zombification

答案 1 :(得分:1)

有关游戏架构的一些好资源可以帮助您入门游戏,"Good resources for learning about game architecture"?。通常,一个好的做法是将游戏组件分解为单个概念。在这个简单的场景中,我会将僵尸列表作为Game类的一个组件,并在其上有一个方法FindClosest(PositionOfHero)。该窗口仅启动正确的对象图,而不是将图之间的链接保持为全局数组。