2017-06-22 153 views
2

所以我正在用p5js框架做這個突破遊戲,但是在檢查球是否碰到塊時我有點卡住了。我把所有的塊都作爲一個數組中的一個對象,每循環遍歷數組來檢查它是否與球碰撞,但不知何故我的if語句無法正常工作。Js if語句無法正常工作

這是我的循環是什麼樣子:

for(var i=0; i<blocks.length; i++){ 
     if(this.x <= (blocks[i].x + 10) && this.x >= (blocks[i].x - 10)){ 
     //the + and - 10 stand for the length of the block which is 20 and is drawn from the center 
      console.log(blocks[i], this.x, this.y); 
      if(this.y <= blocks[i].y + 10 && this.y >= blocks[i].y + 5){ 
      //here the + 10 stands for the height of the block/2 + the height of the ball/2 and the + 5 stands for the height of the height of the block/2 
       console.log('yes'); 
      } 
     } 
    } 

你可以看到,我CONSOLE.LOG()當前塊和球x和y的位置,如果它的x位置是否符合要求,但如果我登錄它,我得到這樣的結果:

block {x: "70", y: "315", c: "white"} 200 470 
//I get a lot more results but this is an example. 

,但是這不應該被記錄,因爲70 + 10 也是我第二次的console.log()永遠不會觸發。

這是我的球對象的變量是這樣的:

this.x = x; 
this.y = y; 
this.r = 10; 

其中r爲球的半徑。

這是塊對象是什麼樣子:

this.x = x; 
this.y = y; 

我希望有人可以提供幫助。

回答

2

我認爲問題在於您的block.x是一個字符串而不是數字。你可以在瀏覽器的控制檯驗證這一點:

console.log(200 < "70" + 10) // true 
 
console.log(200 > "70" - 10) // true

這是因爲"70" + 10將產生"7010",但"70" - 10將產生60(上JS如何決定字符串轉換爲數字或很有趣不是在這些情況下,對吧?)。您需要使用parseInt()方法將block.xblock.y轉換爲數字。例如。

console.log(200 < parseInt("70") + 10) // false

+0

謝謝我認爲這是答案我會在今天晚些時候嘗試它 –

+0

是的,它的工作非常感謝你 –

1
block {x: "70", y: "315", c: "white"} 200 470 

VAR X: 「70」 的typeof字符串相同的變種Ÿ.. 你可以嘗試parseFloat(x)/parseInt(x)將變更爲數字。