javascript游戏如何减少主窗口中实体的耦合?
我在游戏中有一个实体,它有一个更新方法,它需要以最近的僵尸为目标,目前僵尸列表只是我访问的一个全局对象,但这似乎是错误的,我可以将列表传递到更新方法中,但我不确定这是否是最好的方法 以下是我的更新方法的简化版本:javascript游戏如何减少主窗口中实体的耦合?,javascript,Javascript,我在游戏中有一个实体,它有一个更新方法,它需要以最近的僵尸为目标,目前僵尸列表只是我访问的一个全局对象,但这似乎是错误的,我可以将列表传递到更新方法中,但我不确定这是否是最好的方法 以下是我的更新方法的简化版本: this.update = function () { var targetedZombie = null; //TODO: should not be using the zombies object - tight c
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
(功能(全局){
var zombies=[];//仅可供您访问
函数zombieManager(){
this.addZombie=函数(){zombies.push()}
this.killHalfZombies=函数(){
zombies=zombies.filter(函数(项,i){返回i%2==0});
}
}
global.zombieManager=新的zombieManager();
函数英雄(){
};
hero.prototype.update=函数(){
//挖掘僵尸[]
//做任何状态改变
};
global.hero=英雄;
})(窗口)// gamedev上有一些关于游戏架构的好资源,可以帮助您入门。一般来说,一个好的做法是将游戏的组成部分分解为单个概念。在这个简单的场景中,我将使僵尸列表成为游戏类的一个组件,并在其上有一个FindClosest(PositionOfHero)方法。该窗口只会启动正确的对象图,而不会将图之间的链接作为全局数组持久化。使用单例的有用想法,尽管这仍然会将zombies数组暴露给整个API,除非我遗漏了什么,否则api将有效地贯穿整个游戏?难道僵尸不应该适用于你的整个api/游戏吗。上面的示例演示了如何不将一个主数据耦合到可公开写入的窗口属性。感谢链接,我认为我已经对基本概念有了合理的理解,将僵尸作为组件仍然意味着英雄需要将组件的实例作为全局对象(封装阵列的组件和仅公开阵列本身的组件之间没有太大区别?)