0

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;
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
Dom Tory
  • 1
  • 4
  • Please post code as text, not an image. – D Stanley Dec 10 '14 at 14:57
  • @D Stanley Woops very sorry, didn't mean to post as an image haha! – Dom Tory Dec 10 '14 at 14:59
  • I think we miss some code here. You're supposed to have a bunch of bricks, so why am I not seeing `picBrk[i]` instead of `pcBrk1` (for example) in your condition? EDIT: nvm, you have 5 bricks in total. Well you should start by putting them in a List and loop it :p – Kilazur Dec 10 '14 at 15:10

1 Answers1

0

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
Lau Lu
  • 23
  • 4