Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simpler way to check for collision?

I'm working on an assignment for uni where I have to create a Breakout game in Visual Studio 2010 using C# Win Forms. At the moment, I am concentrating on there being only one brick to be destroyed so I have the mechanics down before expanding on it.

To clarify about my current program: I am using a picture box as a Graphics object and a timer to create the animation effect. The ball can skip, at each frame, between 1 and 10 pixels — this is part of creating a random starting vector for the ball.

This works fine until it comes to checking if the ball has 'hit' the brick I have drawn. What I have is an if statement that checks if the ball is at any of the coordinates on the picture box that corresponds to the outline of the brick. I know that the logic is fine because it works some of the time. However, because of the variation in the 'jumping' of the ball's position, I need to add a buffer area of +/- 5 pixels to my if statement.

This is where the problem arises, because my if statement (two, really) is really complicated as it is:

// Checks if ball hits left side or top of brick
if (((x >= brickX) && (x <= (brickX + 50)) && (y == brickY)) ||
    ((y >= brickY) && (y <= (brickY + 20)) && (x == brickX)))
{
    brickHit = true;
}
// Check if ball hits right side or bottom of brick
else if ((((x >= brickX) && (x <= brickX + 50)) && (y == (brickY + 20))) ||
    (((y >= brickY) && (y <= brickY + 20)) && (x == brickX + 50)))
{
    brickHit = true;
}

For clarification: x and y are the coordinates of the ball and brickX and brickY are the coordinates of the top-left corner of the rectangle brick (which is 50 pixels wide, 10 pixels high).

Is there any way to simplify the above if statements? If I can make them simpler, I know it'll be much easier to add in the 'buffer' (which only needs to be 5 pixels either side of the brick's outline' to allow for the ball's change in position).

If further clarification is needed, please ask — I'm writing this question at 5:12am so I know I might be a little unclear.

like image 969
Saladin Akara Avatar asked Feb 25 '23 20:02

Saladin Akara


2 Answers

One way you could possible simplify this (and I may be misunderstanding your spec), but you can make a Rectangle out of the bounds of the brick and check the Contains for your x,y point.

Rectangle rec = new Rectangle(brickX, brickY, 50, 20);
rec.Offset(-5, -5);
rec.Inflate(10, 10);
if (rec.Contains(new Point(x,y))
{
    brickHit = true;
}
like image 84
pstrjds Avatar answered Mar 06 '23 23:03

pstrjds


brickHit = new Rectangle(brickX,brickY,50,20).Contains(x,y);

Adding a buffer:

int buffer = 5;
brickHit = new Rectangle(brickX,brickY,50,20).Inflate(buffer,buffer).Contains(x,y);

The Rectagle class can come in handy sometimes.

like image 23
Lilith River Avatar answered Mar 06 '23 21:03

Lilith River