2013-03-08 54 views
-2

我不能让我的VAR计数跟踪计数的if语句谁能帮助我我不能让我的变种数右

Laser.prototype.update = function() { 
    //.3 
    this.rot += .3 
    this.pos.add(this.dir.clone().mult(5)); 
    this.alive = !(this.pos.x > cw || this.pos.x < 0 || this.pos.y > ch || this.pos.y < 0); 
    var counts = 0; 
    for (var i = 0; i < asteroids.length; i++) { 
     var astPos = asteroids[i].pos.clone(); 
     astPos.sub(this.pos); //3 impact area 
     if (asteroids[i].onscreen && astPos.len() < asteroids[i].sizes[asteroids[i].level] + 10) { 
      asteroids[i].hit(this.dir); 
      if (counts < 5) { 
       this.alive = false; 
       counts++; 
       //alert("the count is" + counts); 
      } 
      if (counts > 5) { 
       this.alive = true; 
       counts++; 
       alert("the count is" + counts); 
      } 
      return counts; 
     } 
    } 
} 
+3

究竟是什么问题?它根本不算数吗?它在某些情况下不计算在内吗?它跳过数字吗?有错误吗?你有什么想法“它应该如何计数”? – newfurniturey 2013-03-08 04:08:15

+0

让我猜:' .update()'总是返回'1'? – Passerby 2013-03-08 04:09:01

+1

提示:使用'console.log'而不是'alert'。你已经提供了代码 - 这很好 - 但你忘了在你的问题中实际提出一个问题。 – Phrogz 2013-03-08 04:09:56

回答

3

可能是你没有考虑当数= = 5,因此它不执行计数++可言,当计数到达5.您可以将if条件的代码更改

if (counts<5){ 

      this.alive = false; 
      counts++; 
      //alert("the count is" + counts); 
} 
else{ 

      this.alive = true; 
      counts++; 
       alert("the count is" + counts); 

} 

或类似的东西...来考虑的话,当计数== 5.

编辑:也将return语句放在for循环之外。尝试然后

EDIT2:也改变了if语句

if (asteroids[i].onscreen && (astPos.len() < (asteroids[i].sizes[asteroids[i].level] + 10))) {

赋予了它更好的可读性

EDIT3:考虑下面的评论中,有两件事情你可以试试。

  1. 将return语句放在for循环之外。这样

    if (counts > 5) { 
            this.alive = true; 
            counts++; 
            alert("the count is" + counts); 
           } 
          } 
         } 
         return counts; 
        }

  2. 或者,你可以宣布“罪状”作为一个全局变量,并增加了“计数”,在你的函数,你在评论有。并返回它。在这种情况下,for循环没有多大意义。那么你可以删除它。试试这个,让我们知道。

+0

为了一个好的猜测+1。 – Phrogz 2013-03-08 04:11:40

+0

我已经考虑过,但它穿的工作,我想要的功能后,我可以得到的功能,以保持计数权利,我将有一个其他语句,重置计数器后2秒如果语句达到一个检验点 – 2013-03-08 04:16:26

+1

你是否也在其他地方使用“计数”这个名字?并希望它会有助于改变你所显示的代码的“数量”(因为,你说你已经考虑过了)。因为,正如你在这里声明“var counts”一样,它只是函数的局部。并且在计数== 5时也会中断。 – Archer 2013-03-08 04:21:46