我正在嘗試爲我製作的遊戲創建一個簡單的背景,並且每次運行循環時都需要我的函數的新實例。在循環中創建函數的新實例
以前我曾嘗試打電話給我的功能像這樣:
Sprite();
Sprite();
Sprite();
Sprite();
Sprite();
Sprite();
Sprite();
這個工作,創建了功能的幾個實例。但是,當我在一個循環中嘗試這個時,它只創建10個相同的實例,而不是再次將其作爲新實例調用。
我已經嘗試的代碼是:
for(var i = 0; i <= 10; i++){
Sprite();
setTimeout(Sprite, 1000);
}
function Sprite(){
// set the sprite properties
this.r = 30 * Math.random().toFixed(2);
this.x = Math.floor(Math.random(Math.random()) * 5000); //Start position
this.y = Math.floor(Math.random(Math.random()) * 5000); //Start position
this.dx = Math.floor(this.x + this.r); //Destination position
this.dy = Math.floor(this.y + this.r); //Destination position
this.s = Math.random(Math.random()).toFixed(2)* 5000;
this.active = true;
//create the sprite
var div = document.createElement('div');
div.id = 'block';
div.className = 'block';
document.getElementsByTagName('body')[0].appendChild(div);
// call the animate function
animSprite();
// logging output
console.log("sprite has been created: \nthis.r = " + r + "\nthis.x = " + x + "\nthis.y = " + y + "\nthis.dx = " + dx + "\nthis.dy = " + dy + "\nthis.s = " + s + "\nanimSprite() = true");
}
上述調用下面的動畫的div: //動畫精靈
function animSprite(n){
//will need a switch case to determine which shape has which properties
switch(n){
case 1:
// animate the div
$('.block').animate({
top: this.y,
right: this.x
}, this.s);
break;
case 2:
// animate the div
$('.block').animate({
top: this.y,
bottom: this.x
}, this.s);
break;
case 3:
// animate the div
$('.block').animate({
bottom: this.y,
right: this.x
}, this.s);
break;
case 4:
// animate the div
$('.block').animate({
left: this.y,
bottom: this.x
}, this.s);
break;
}
}
我在哪裏出了錯?如何我修正它就好像每次循環運行時都會調用一個新函數?我更喜歡jQuery免費解決方案,但我願意使用它。
只是調用一個函數和創建一個函數是有區別的一個類的實例(這是一個函數)?看起來你只是多次調用同一個函數。作爲旁註,你的for循環只迭代一次,而不是十次? – adeneo
你能向我們展示Sprite實現嗎? – ItayB
實際上,自從你先調用它然後設置一個超時來調用它,你實際上已經調用了sprite約20次了。 –