我在游戏中有一个实体,它有一个更新方法,它需要定位最近的僵尸,目前僵尸列表只是我访问的全局对象,但这似乎是错误的,我可以将列表传递到更新中方法,但我不确定这是否是最好的方法?
这是我的更新方法的简化版本:
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);
}
});
最佳答案
使用闭包 //初始化你的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
关于javascript游戏我应该如何减少实体与主窗口的耦合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10287665/