我目前有一个球从画布的墙壁上弹起。我在屏幕中间添加了一个矩形。每当球与矩形碰撞时,我也希望球也弹回矩形,但是我不知道该怎么做。我有一个名为“ r”的矩形。

如何使球将矩形视为壁并在碰到矩形时改变方向?代码示例将不胜感激。谢谢。

这是我的球从墙上弹起的代码:

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

最佳答案

我不知道JavaFx,但这是个主意:

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
}


但是,还有更好的和可扩展的解决方案(用于编写突破性砖块)。

09-10 20:03