2017-06-22 154 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)将变更为数字。