Collision Detection

Hey guys. I’m working on the collision detection for my brickbreaker game. Originally, I was just checking if the rectangles of the ball and the brick overlapped…As you can imagine, this won’t work, so it’s time to upgrade and fix it. I’m wondering what the best way to implement it would be…I was in the process of doing


if (ballRect.x >=brick.brickRect.x && ballRect.x <=brick.brickRect.x && ballRect.y >=brick.brickRect.y && ballRect.y <= brick.brickRect.y )

But there has to be a better way…plus that way isn’t working lol

I don’t see anything wrong with your overlapping idea…

if(ballRectangle.intersects(blockRectangle))

works perfectly fine

I’m trying to make it a little more accurate to tell which direction of the ball to change.

I’ve got


if (brick.brickRect.overlaps(ballRect))
		{
			if (brick.brickRect.x <= ballRect.x+ballRect.width) ballSpeedX = -ballSpeedX;
			if (brick.brickRect.x + brick.brickRect.width >= ballRect.x) ballSpeedX = -ballSpeedX;
			if (brick.brickRect.y <= ballRect.y + ballRect.height) ballSpeedY = -ballSpeedY;
			if (brick.brickRect.y + brick.brickRect.height <= ballRect.y) ballSpeedY = -ballSpeedY;


I wish I could get over this damn learning curve. I’m working at it though.

The “overlaps” part probably isn’t necessary if you have those if statements. Anyways, there are multiple problems with your code; for one you should re-check those conditions - shouldn’t it be

if (brick.brickRect.x <= ballRect.x)

not

if (brick.brickRect.x <= ballRect.x + ballRect.width)

? Not to mention that all of your conditions should be in one if statement, otherwise it will incorrectly detect collision when only the x is satisfied, and not the y, for example.

Yeah, I definitely need to rewrite it. I’m tired so I think it’s just getting a little sloppy. The ballrect.x + ballrect.width is to get the right side of the ball.

hmmm after you use the intersects method find which side should be trivial.

In order for a object to move there must be a velocity right? Or some value you are incrementing by. Check to see if that value is positive or negative. Do this for both X and Y. Not to correct the collision you would need to find how much these objects intersect and subtract or add to the X and Y. Well look around at some Rectangle2D stuff in java and you will find what you are looking for.

I simply use this when detected collision.


public void processCollision(Ball ball, Block block)
{
    int xdist = Math.abs(ball.centerX - block.centerX);
    int ydist = Math.abs(ball.centerY - block.centerY);
    if (xdist>ydist)
    {
        // Collision on top or bottom of block
        ball.vspeed = -ball.vspeed;
    }
    if (ydist>xdist)
    {
        // Collision on left or right of block
        ball.hspeed = -ball.hspeed;
    }
    block.destroy();
}