0

I'm new to JavaScript and I'm trying to code a somewhat simplified version of the breakout game. It is not done yet, and pretty messy regarding the coding, but it works, almost. My collision detector has some trouble detecting the ball. It does what it is supposed to for the most part, but from time to time the ball just goes straight through, and I cannot figure out how to remake that part.
The code looks like this

    function collisionDetection(){
  for(var c=0; c<brickColumnCount; c++){
    for(var r=0; r<brickRowCount; r++){
        var b=bricks[c][r];
        //collisionDetection
        if(b.status == 1){
        if(x+15 > b.x && x+15 < b.x+brickWidth && y-10 > b.y && y-10 < b.y+brickHight){
        dy = -dy;
        b.status = 0;
        score++;
        color = getRandomColor();
        } 
      }
    }
  }
}

I made the paddle as long as the canvas for testing - I have not yet made something to get the ball to change the angle, only speed. And I haven't defined a maxSpeed yet which I will do later on, but first I want my collision to work properly.

Do you have an idea why this is not working? I noticed that at 200 points the collision will not work at all. Might be the speed(Which is insanely high, yes)?

The full code can be found here

Thanks

1 Answers1

0

If the x and y values are the top left corners of your ball and brick elements, then the if statement should probably be:

        if (x + 15 > b.x && x < b.x + brickWidth && y + 15 > b.y && y < b.y + brickHight)

For proper collision detection you'll have to implement some side detection as well. I.e. if the ball hits the side of the brick, dx must be reversed and not dy.

Sev
  • 348
  • 2
  • 6