i have a logic problem that maybe you smart guys can help me to resolve. I am learning Javascript with Canvas and i'm trying to build a sort of "brakeout" game using pure Javascript.
http://www.seas.upenn.edu/~cis120e/hw/SwingGame/images/breakout.png
I created the paddle, the ball, and then an array of blocks-Objects with different properties(xPos, yPos, width...etc), now i am trying to detect the collision of the ball with the blocks on the top of the screen.
This is the way i do:
//This is my block Object definition
function block(x,y,width,height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
ctxBlock.fillStyle = 'green';
ctxBlock.fillRect(this.x, this.y, this.width, this.height);
}
//This is for draw blocks on the canvas
mattone.prototype.draw = function(){
ctxBlock.fillStyle = 'green';
ctxBlock.fillRect(this.x, this.y, this.width, this.height);
}
//This is the check for collision method
var blocks = [];
function checkCollision(){
for (var i = 0; i < blocks.length; i++){
if(ballY - ballRadius <= blocks[i].y + blockWidth){
ctxBlocks.clearRect(tmpx, tmpy, blockWidth, blockHeight);
speedY = (-speedY);
break;
}
}
checkColl = requestAnimationFrame(checkCollision);
}
Basically i am trying to tell the canvas that when the "Y" of the ball is "<" then the "Y" of one of the block in the array of blocks(looping trough and checking for every single block), he must delete that block and bounce down.
But what it does is always cancel the first block on the left in that line of blocks, and not the block he touch.
This should be the link to my code link *Plese note i used the word mattoni instead of block in my code
Have a nice day to you all
jsfiddle.net?