我正在搞亂JavaScript遊戲開發,我有一個加載數組中的精靈的問題。它可以很好地更新這個「怪物」類,但是當我使用for-loop來更新它們時,精靈會自動重複。 更新數組中的Sprite與For循環
下面是與sprite加載器相關的代碼以及sprite本身的代碼。
MobLoader
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();
}
}
}
敵對階級(雜草)
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);
我已經這樣做了,我認爲問題來自for循環更新實體 – user1994100 2014-10-12 01:11:53
你好..你有沒有嘗試過ctx .clearRect而不是ctx.fillRect清除畫布? – d13 2014-10-12 12:23:34