所以我正在用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;
我希望有人可以提供幫助。
謝謝我認爲這是答案我會在今天晚些時候嘗試它 –
是的,它的工作非常感謝你 –