【问题标题】:Js if statement is not working properlyjs if 语句不能正常工作
【发布时间】:2017-11-25 15:14:21
【问题描述】:

所以我正在使用 p5js 框架制作这个突破性游戏,但是在检查球是否击中积木时我有点卡住了。我将所有的块都作为一个对象放在一个数组中,我在每一帧都循环遍历数组以检查它是否与球发生碰撞,但不知何故我的 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

这就是我的球对象的变量的样子:

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

以 r 为球的半径。

这是块对象的样子:

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

希望有人能帮忙。

【问题讨论】:

    标签: javascript object for-loop if-statement


    【解决方案1】:
      block {x: "70", y: "315", c: "white"} 200 470
    

    var x: "70" typeof String 与你的 var y.. 你可以试试parseFloat(x)/parseInt(x)会变成数字。

    【讨论】:

      【解决方案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 &lt; parseInt("70") + 10) // false

      【讨论】:

      • 谢谢,我想这就是我今天晚些时候会尝试的答案
      最近更新 更多