Brickbreaker C# (ball-brick collision detection)

1.1k views Asked by At

I am currently creating a brickbreaker clone (yeah, another) and have the ball-brick collision for 1 brick. I have 4 other bricks commented out, because when the ball collides with the brick I have the right code for, it just removes all bricks rather than the specific one it collided with. Also, the ball only collides with the first brick when the ball is near the top left corner of the game screen (pretty far from the actual brick). I'm really not sure what to do, I have tried spacing the bricks out a bit more but that didn't help.

int score = 0;
if ((ballY > picBrk1.Height) && (ballY < picBrk1.Height + 30) && (ballX > picBrk1.Width) && (ballX < picBrk1.Width + 71))
{
    // ball rebounds off brick
    yChange = -yChange;

    // each brick adds 1 to score
    score = score + 1;
    lblScore.Text = "Score: " + score;

    picBrk1.Visible = false;
}
1

There are 1 answers

0
Lau Lu On

You need to be very clear about the localisation of your bricks. I suggest adding a UpperLeft property to your Brick class:

public class Brick
{
    /* your other properties here */

    public Point UpperLeft {get; set;}
}

Make sure UpperLeft value is properly set to the coordinates of the upper left corner of your brick. My assumption is that your X and Y follow the standard computer image representation where 0,0 is the top left corner of the image and y increases when you go south (which is different from the usual mathematical standard). Then your collision check will be:

Point ballRelativeToBrick1 = new Point(
    ballX - picBrick1.UpperLeft.X,
    ballY - picBrick1.UpperLeft.Y)
bool collide = 0 < ballRelativeToBrick1.X && ballRelativeToBrick1.X < picBrick1.Width
    && 0 < ballRelativeToBrick.Y && ballRelativeToBrick.Y < picBrick1.Height