How to make ball bounce off an object in Javafx?

2019-09-15 09:43发布

问题:

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();
    }

回答1:

I don't know JavaFx but here is the idea :

while (1) {
    bool btop = pos.y >= top
    bool bbottom = pos.y <= bottom
    bool bleft = pos.x <= left
    bool bright = pos.x >= right
    bool rect_btop = pos.y <= rect_top && pos.x >= rect_left && pos.x <= rect_right
    bool rect_bbottom = pos.y <= rect_bottom && pos.x >= rect_left && pos.x <= rect_right
    bool rect_bright = pos.x <= rect_right && pos.y >= rect_bottom && pos.y <= rect_top
    bool rect_bleft = pos.x >= rect_left && pos.y >= rect_bottom && pos.y <= rect_top

    if (btop || bottom || rect_btop || rect_bbottom)
        vy -= vy

    if (bleft || bright || rect_bleft || rect_bright)
        vx -= vx
}

There are however far better and scalable solution (to code a breakout bricks).