I currently have a ball bouncing off the walls of the canvas. I added a rectangle in the middle of the screen. Whenever the ball collides with the rectangle, I want it to bounce off it too, but I don't know how to do that. I have a rectangle called "r".
How do I make the ball treat the rectangle as a wall and change direction whenever it hits it? Code examples will be greatly appreciated. Thanks.
Here's my code for the ball bouncing off the walls:
public void handle(ActionEvent t) {
// Moves the ball depending on the values of X and Y
circle.setLayoutX(circle.getLayoutX() + X);
circle.setLayoutY(circle.getLayoutY() + Y);
final Bounds bounds = canvas.getBoundsInLocal();
// Boolean values to check if a wall has been hit
boolean leftWall = circle.getLayoutX() <= (bounds.getMinX() + circle.getRadius());
boolean topWall = circle.getLayoutY() <= (bounds.getMinY() + circle.getRadius());
boolean rightWall = circle.getLayoutX() >= (bounds.getMaxX() - circle.getRadius());
boolean bottomWall = circle.getLayoutY() >= (bounds.getMaxY() - circle.getRadius());
// If the bottom or top wall has been touched, the ball reverses direction.
if (bottomWall || topWall) {
Y = Y * -1;
}
// If the left or right wall has been touched, the ball reverses direction.
if (leftWall || rightWall) {
X = X * -1;
}
}
}));
loop.setCycleCount(Timeline.INDEFINITE);
loop.play();
}