Javascript 使用For循环更新阵列中的精灵

Javascript 使用For循环更新阵列中的精灵,javascript,html,Javascript,Html,我在玩JavaScript游戏开发,在从数组加载精灵时遇到了问题。单独更新这个“mob”类效果很好,但当我使用for循环更新它们时,精灵会自动跟踪并重复。 下面是与精灵加载程序关联的代码,以及精灵本身的代码 移动装载机 function mobloader(){ var self = this; for (c = 0; c < 3; c++){ var t = new enemy(rInt(10, 400), rInt(10,400));

我在玩JavaScript游戏开发,在从数组加载精灵时遇到了问题。单独更新这个“mob”类效果很好,但当我使用for循环更新它们时,精灵会自动跟踪并重复。

下面是与精灵加载程序关联的代码,以及精灵本身的代码

移动装载机

function mobloader(){
    var self = this;
    for (c = 0; c < 3; c++){
        var t = new enemy(rInt(10, 400), rInt(10,400));
        enemies.push(t);
    }
    self.updatemobs = function(){
        for (l = 0; l < enemies.length; l++){
            enemies[l].updatemob();
        }
    }
}

您需要在重新绘制框架之前清除画布。

我同意上面的答案。使用console.log检查它是否实际运行,如果不起作用,请将bgcolor替换为“rgb”255255,0“只是为了测试,因为那里可能有问题。唯一的另一件事是,每次他行走/帧更新时,您都会生成一个实体。但是我非常非常怀疑。

我已经这么做了,我认为问题来自for循环更新entitiesHello。。您是否尝试过ctx.clearRect而不是ctx.fillRect来清除画布?
function enemy(x, y){
    var self = this;
    self.x = x;
    self.y = y;
    self.name = "Jake";
    self.enemyspr = new sprite("grasstest.png", self.x, self.y, 40, 40, 1, 1, 0, false);
    self.updatemob = function(){
        for (s = 0; s < spells.length; s++){
            if (spells[s].cy >= self.enemyspr.y && spells[s].cy <= self.enemyspr.y + self.enemyspr.h && spells[s].cx <= self.enemyspr.x + self.enemyspr.w && spells[s].cx >= self.enemyspr.x && self.enemyspr.active == true ){
                self.enemyspr.active = false;
                spells[s].spellspr.active = false;
            }
        }
        self.enemyspr.update();
    }
}
function sprite(src, x, y, w, h, f, l, a, loaded){
    var self = this;
    self.src = src;
    self.x = x;
    self.y = y;
    self.w = w;
    self.h = h;
    self.cf = 0;
    self.f = f;
    self.cl = 0;
    self.l = l;
    self.active = true;
    self.a = a;
    self.cfps = 0;
    self.fps = 10;
    self.loaded = loaded;
    self.spr = new Image();
    self.spr.onload = function(){self.loaded = true;}
    self.spr.src = self.src;    
    self.update = function(){
        if (self.active == true){
            self.cfps += 1;
            if (self.cfps > self.fps && self.a == 1){
                self.cfps = 0;
                self.cf += 1;
                if (self.cf >= self.f){
                    self.cf = 0;
                }
            }
            if (self.a == 3){
                if (self.f > 9){
                    self.cl = Math.floor(self.f / 10);
                    self.cf = self.f - (Math.floor(self.f / 10) * 10);
                }
                if (self.f <=9){
                    self.cf = self.f;
                    self.cl = self.l;
                }
            }
            ctx.drawImage(self.spr, self.w * self.cf, self.h * self.cl, self.w, self.h, self.x, self.y, self.w, self.h);
        }
    }
}
function gameupdate(){
    ctx.fillStyle = bgcolor;
    ctx.fillRect(0, 0, c.width, c.height);
    updategame();
}
setInterval(gameupdate, 16);