所以我正在使用 p5js 框架制作这个突破游戏,但是在检查球是否击中障碍物时我有点卡住了。我将我的所有 block 作为数组中的一个对象,我在每一帧循环遍历该数组以检查它是否与球碰撞但不知何故我的 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() 当前 block 和球的 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 < 200。 我的第二个 console.log() 也永远不会触发。
这是我的球对象的变量:
this.x = x;
this.y = y;
this.r = 10;
以r为球的半径。
这是 block 对象的样子:
this.x = x;
this.y = y;
我希望有人能提供帮助。
最佳答案
我认为问题在于您的 block.x
是字符串而不是数字。您可以在浏览器的控制台中验证这一点:
console.log(200 < "70" + 10) // true
console.log(200 > "70" - 10) // true
这是因为 "70"+ 10
会产生 "7010"
,但是 "70"- 10
会产生 60
(关于 JS 如何决定在这些情况下是否将字符串转换为数字非常有趣,对吧?)。您需要使用 parseInt()
方法将 block.x
和 block.y
转换为数字。例如
console.log(200 < parseInt("70") + 10) // false
关于javascript - Js if语句不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44697736/