jeudi 22 juin 2017

Js if statement is not working properly

So I am making this breakout game with the p5js framework, but I am a bit stuck when checking if the ball is hitting the blocks. I have all my block as an object in an array and I loop through the array every frame to check if it collides with the ball but somehow my if statement doesn't work properly.

this is what my loop looks like:

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');
            }
        }
    }

You can see that I console.log() the current block and the balls x and y position if its x position meets the requirements but if I log it I get this result:

block {x: "70", y: "315", c: "white"} 200 470
//I get a lot more results but this is an example.

but this shouldn't be logging because 70+10 < 200. Also my second console.log() never triggers.

this is what the variables of my ball object look like:

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

with r as the radius of the ball.

this is what the block object looks like:

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

I hope someone can help.

Aucun commentaire:

Enregistrer un commentaire