【发布时间】: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