So I'm creating a breakout game and everything's going well, except certain collisions with bricks. I don't know how to go about detecting if the ball hits the brick from the left or the right. I'm trying to create an if statement that reads "if the ball hits the brick from the left or the right, xSpeed is multiplied by -1, else if the ball hits the brick from the top or bottom, y is multiplied by -1." This is easy to do, but detecting where the brick is hit has me stumped. I'm using javafx. I'm sure it's easy, I'd just like to figure out how I should start.
Asked
Active
Viewed 752 times
-1
-
1Can you post the collision-detection code you're using? It may help you get a more specific answer. – Will Angley Apr 28 '15 at 22:29
-
1I can't, I'm doing it for a project for school and we're not allowed to post code. I want just a general answer and I can probably write the code after I get an idea – dracula90 Apr 28 '15 at 22:32
2 Answers
0
Make a collision box around the brick and the ball and compare the position values, something like this:
Rectangle brickCollision = new Rectangle(x, y, w, h);
Rectangle playerCollision = new Rectangle(x, y, w, h);
//example (collision for one side)
if(playerCollision .x + playerCollision.w > brickCollision.x && playerCollision.x < brickCollision.x + brickCollision.w){
System.out.println("Collision");
}

Christian Benner
- 104
- 7
-
Ya I can detect collisions right now, my problem is that I can't tell which side the ball hits. I guess I could make four collision, one on each side and go from there, but that could get complicated. Is there an easier way to do this? – dracula90 Apr 28 '15 at 22:40
-
I don't think it would be too complicated. You only need two branches, one for top/bottom, and one for left/right collision. – biziclop Apr 28 '15 at 22:44
0
This is not java fx specific:
You have probably a setup for the grid with grid_x and grid_y coordinates to indicated a brick or empty spot.
When collision occurs, you know the grid position of the ball Bl_xy (which has to be an empty spot) and the grid position of the brick Br_xy which was hit.
Now, if the empty spot Bl_xy is above or below of the brick Br_xy, you need to change the vertical speed component for the ball.
If the empty spot Bl_xy is left or right from Br_xy, change the horizontal speed.
I hope this helps on your super secret school project.

mrak
- 2,826
- 21
- 21