2014-01-26 3 views
0

Я пытаюсь создать простой фон для игры, которую я создаю, и каждый раз, когда мой цикл работает, требуются новые экземпляры моей функции.Создать новый экземпляр функции во время цикла

Ранее я попытался назвать свою функцию так:

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"); 
} 

выше называет следующие анимировать дивы: // анимировать спрайт

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, но я открыт для его использования.

+3

Существует разница между просто вызовом функции и созданием ew экземпляр класса (который является функцией)? Похоже, вы просто вызываете одну и ту же функцию несколько раз. Как побочный элемент, ваш цикл for только повторяется один раз, а не десять? – adeneo

+1

Вы можете показать нам реализацию спрайтов? – ItayB

+1

На самом деле вы вызываете спрайт примерно 20 раз, так как вы его вызываете первым, а затем устанавливаете таймаут, чтобы называть его –

ответ

1

Если я вас правильно понял, это то, что вы пытаетесь достичь:

Demonstration

(function() { 
    "use strict"; 

    function Sprite() { 
     var ele = null; 

     this.s = Math.random().toFixed(2) * 5000; 
     this.r = Math.random().toFixed(2) * 30; 
     this.x = Math.floor(Math.random() * 5000); 
     this.y = Math.floor(Math.random() * 5000); 
     this.dx = Math.floor(this.x + this.r); 
     this.dy = Math.floor(this.y + this.r); 
     this.active = true; 

     if (typeof Sprite._div === "undefined") { 
      Sprite._i = 0; 
      Sprite._div = document.createElement("div"); 
      Sprite._div.id = "block"; 
      Sprite._div.className = "block"; 
     } 

     ele = Sprite._div.cloneNode(true); 
     document.body.appendChild(ele); 

     animSprite.call(this, ++Sprite._i, ele); 
    } 

    function animSprite(n, ele) { 
     var obj = null; 
     switch (n % 4) { 
      case 0: 
       obj = { 
        top: this.y, 
        right: this.x 
       }; 
       break; 
      case 1: 
       obj = { 
        top: this.y, 
        bottom: this.x 
       }; 
       break; 
      case 2: 
       obj = { 
        bottom: this.y, 
        right: this.x 
       }; 
       break; 
      case 3: 
       obj = { 
        left: this.y, 
        bottom: this.x 
       }; 
       break; 
     } 
     $(ele).animate(obj, this.s); 
    } 
    for (var i = 1; i <= 50; i++) { 
     setTimeout(function() { 
      new Sprite(); 
     }, i * 1000); 
    } 
}()); 
0

Это связано с тем, что setTimeout() не останавливает выполнение кода, код продолжает работать, и есть несколько переписанных вызовов. Я рекомендую сделать setInterval() после цикла for или просто распечатать его на консоли.

Например, используя свойство для ясности:

function Sprite(name){ this.name = name; console.log(name); } 

var array = ['a','b','c','d','e','f','g','h','i','j'] 
for(var i = 0; i < 10; i++){ 
    Sprite(array[i]); 
} 

http://jsfiddle.net/4Y5se/

Смежные вопросы