Анимация JavaFX не работает в области стека - PullRequest
0 голосов
/ 26 марта 2020

Я работаю над заданием класса, игрой в понг. Ниже приведено требование.

Прямоугольный манипулятор angular перемещается вперед и назад с помощью перетаскивания мышью вдоль нижней части панели; Если шар соединяется с веслом, то он отскакивает под углом 90 градусов обратно в пространство панели;

Действия мыши и клавиатуры не работают должным образом, нет реакции на мышь и клавиши.

Я не могу понять проблему. Будем благодарны за любую помощь.

PongForOne. java

public class PongForOne extends Application {
    @Override
    public void start(Stage primaryStage) {
        BallPane ball = new BallPane();
        PaddlePane paddle = new PaddlePane();
        StackPane stkPane = new StackPane();

        stkPane.getChildren().addAll(paddle,ball);

        paddle.setOnMouseDragged(e -> {
            PaddlePane.paddle.setX(e.getX());
        });

        paddle.setOnKeyPressed(e -> {
            switch(e.getCode()){
                case LEFT:  PaddlePane.paddle.setX(PaddlePane.paddle.getX() - 10);  break;
                case RIGHT: PaddlePane.paddle.setX(PaddlePane.paddle.getX() + 10);  break;
                default: break;
            }
        });

        Scene scene = new Scene(stkPane, 300, 400);
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();

        ball.requestFocus();
        paddle.requestFocus();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

BallPane. java

public class BallPane extends Pane {
    private final double radius = 20;
    private double x = radius, y = radius;
    private double dx = 1, dy = 1;
    private int numBallHitsPaddle = 0;
    private int numBallMissPaddle = 0;
    private final Circle circle = new Circle(x,y, radius);
    private final Text text= new Text (x, y, Integer.toString(numBallHitsPaddle));
    private final Timeline animation;

    public BallPane(){
        circle.setFill(Color.GREEN);
        getChildren().addAll(circle, text);
        animation = new Timeline(new KeyFrame(Duration.millis(5), e -> moveBall()));
        animation.setCycleCount(Timeline.INDEFINITE);
        animation.play();
    }
    public void play(){
        animation.play();
    }
    public void pause(){
        animation.pause();
    }
    public void increaseSpeed(){
        animation.setRate(animation.getRate() + 0.1);
    }
    public void decreaseSpeed(){
        animation.setRate(
            animation.getRate() > 0 ? animation.getRate() - 0.1 : 0);
    }
    public void colorChange(){
        circle.setFill(Color.color(Math.random(), Math.random(), Math.random()));
    }
    public DoubleProperty rateProperty(){
        return animation.rateProperty();
    }
    public boolean ballHitsPaddle(){
        boolean status = false;
        if (x + radius > PaddlePane.getPaddleX() && x - radius < PaddlePane.getPaddleX() + PaddlePane.getPaddleWidth() && y + radius == PaddlePane.getPaddleY()){
             status = true;
        }
        return status;
    }
    /**
     * defines ball's movement
     * changes color every time when ball hits paddle and counts the number of hit
     */
    public void moveBall(){
        if (x < radius || x > getWidth() - radius){
            dx *= -1;
        } 
        if ( y > getHeight() - radius){
            x = getWidth() / 2;
            y = 50;
            dx *= -1;
            numBallMissPaddle++;
        }
        if (y < radius || ballHitsPaddle()){
            if(ballHitsPaddle()) {
                text.setText(Integer.toString(++numBallHitsPaddle));
                colorChange();
            }
            dy *= -1; 
        }
        x += dx;
        y += dy;
        circle.setCenterX(x);
        circle.setCenterY(y);
        text.setX(x - 4);
        text.setY(y + 3);
    }   
}

PaddlePane. java

public class PaddlePane extends Pane{
    private static final double width = 40, hight = 5;
    public static Rectangle paddle = new Rectangle(width, hight);


    public PaddlePane(){
        paddle.xProperty().bind(widthProperty().divide(2).subtract(width / 2));
        paddle.yProperty().bind(heightProperty().subtract(100));
        getChildren().add(paddle);
    }
    public static double getPaddleX(){
        return paddle.getX();
    }
    public static double getPaddleY(){
        return paddle.getY();
    }
    public static double getPaddleWidth(){
        return paddle.getWidth();
    }
    public static double getPaddleHeight(){
        return paddle.getHeight();
    }
    public void colorChange(){
        paddle.setFill(Color.color(Math.random(), Math.random(), Math.random()));
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...