我有多个像这样的对象(16)
function Baboo(x,y,size,speed,target,sps,life){
MobRoot.call(this,x,y,size,speed,target,sps,life);
this.spsCoord = [500*0,500*3,500,500];
this.coolDown = 60;
this.atack = 0;}
Baboo.prototype = Object.create(MobRoot.prototype);
Baboo.prototype.throw = function()
{
projectiles.push(new Arrow(this.x,this.y,10,10,this.angle,150,this.target));
}
Baboo.prototype.update = function(){
if(this.life>0)
{
this.sendBack();
this.draw();
this.checkClick();
this.angle = CalculateSlope(this,this.target);
this.directionUpdate();
this.updateBuffs();
this.x += this.direction.x;
this.y += this.direction.y;
}}
/*etc aditional methods*/
继承此对象的所有内容
function MobRoot(x,y,size,speed,target,sps,life)
{
this.size = size*WindowScale;
this.x = x;
this.y = y;
this.angle = 0;
this.speed=speed;
this.colided=false;
this.maxlife = life;
this.life = life;
this.buffArray = [];
this.sps = sps;
this.target = target;
this.direction =
{
x:0,
y:0
}
//x,y,w,h
//ex sprite[0][0] = 0,0,500,500;
this.spsCoord = [];
this.isBoss = false;
}
MobRoot.prototype.directionUpdate = function()
{
this.direction.x = this.speed*Math.cos(this.angle)*-1;
this.direction.y = this.speed*Math.sin(this.angle)*-1;
}
/*aditional methods for mobRoot*/
我希望从数组生成不同的怪物。目前我正在为每种类型分配一个数字(例如:1-Baboo 2-Spider 3-Whatever)并将这些数字存储在数组中,当我生成它们时,我会从数组中为每个mobIndex使用一个开关这个
switch(wave[i])
{
case 1:
mobs.push(new Baboo(arg1,arg2,...));
break;
case 2:
mobs.push(new Spider(arg1,arg2,...));
break;
/*...*/
case 999:
mobs.push(new Whatever(arg1,arg2,...));
break;
}
有没有更优雅的方法来解决这类问题?
答案 0 :(得分:0)
您可以将所有构造函数放入数组中:
var constructors = [Baboo, Spider, Whatever, ...];
if (wave[i] < constructors.length) {
mobs.push(new constructors[wave[i]](arg1, arg2, arg3, ...));
}