2017-06-22 7 views
2

私はp5jsフレームワークでこのブレークアウトゲームを作っていますが、ボールがブロックに当たっているかどうかを確認するときにちょっと立ち往生しています。私はすべてのブロックを配列内のオブジェクトとして持っています。そして、配列とフレームをループして、ボールと衝突するかどうかをチェックしますが、if文は正しく動作しません。Js if文が正常に動作しない

これは私のループは次のようになります。そのx位置が要件を満たしている場合は、現在のブロックとボールのxとyの位置)

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ていることがわかりますが、私はログインしている場合

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

が、70 + 10 また、私の第二にconsole.log()がトリガされませんので、これはログインしてはならない。それは私はこの結果を得ます。ボールの半径Rと

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

これは私のボールオブジェクトの変数がどのように見えるかです。私は誰かが役立つことを願って

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" - 1060を得られます(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:は、あなたのvar yと同じ "70" のtypeof文字列.. あなたはparseFloat(x)/parseInt(x)は数に変わります試すことができます。

関連する問題