0

Пишу игру пинг понг и столкнулся с проблемой движения ракетки. Как её решить?Вот мой вариант:

import javafx.application.Application;
import javafx.scene.shape.*;
import javafx.scene.Parent;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.util.Duration;
import javafx.scene.input.KeyCode;
public class PingPong extends Application {
    Ball ball = new Ball(100, 300); 
    Player rect = new Player();

@Override 
public void start(Stage primaryStage) {
    Pane pane = new Pane();
    pane.getChildren().addAll(rect, ball);
    //-----------------------------------
    rect.setOnKeyPressed(e -> {
        if (e.getCode() == KeyCode.ENTER)
            pane.getChildren().clear();
            rect.moveUp();
            pane.getChildren().addAll(rect, ball);
    });
    //-----------------------------------
    Scene scene = new Scene(pane, 400, 400);
    primaryStage.setScene(scene);
    primaryStage.show();

}

public class Player extends Rectangle {
    private int step = 1;
    public Player() {
        super(10, 50, 30, 200);
    } 
    public void moveUp() {
        rect.setY(rect.getY() + step);
    }
}

public class Ball extends Circle  {
    final static int RADIUS = 15;    
    private int dx = 1, dy = 1;
    private Timeline animation;

    public Ball(int x, int y) {
        super(x, y,RADIUS);
        animation = new Timeline(new KeyFrame(Duration.millis(5), e -> moveBall()));
        animation.setCycleCount(Timeline.INDEFINITE);
        animation.play();
    }


    protected void moveBall() {
            if(ball.getCenterX() < ball.getRadius() || ball.getCenterX() > 400 - ball.getRadius())
                dx *=-1;
            if(ball.getCenterY() < ball.getRadius() || ball.getCenterY() > 400 - ball.getRadius())
                dy *=-1;
            if(collideX() && collideY()) {
                dx *=-1;
                // dy *=-1;
            }
            ball.setCenterX(ball.getCenterX() + ball.dx);
            ball.setCenterY(ball.getCenterY() + ball.dy);

        }
    public boolean collideX() {
        if(ball.getCenterX() - RADIUS  < rect.getX() + rect.getWidth() && ball.getCenterX() > rect.getX())
            return true;
        return false;
    }
    public boolean collideY() {
        if(ball.getCenterY() - RADIUS < rect.getY() + rect.getHeight() && ball.getCenterY() > rect.getY())
            return true;
        return false;
    }
}

}

1 ответ 1

1

Для начала, обработчик событий нужно прописать для сцены, а не для ракетки. Создай перечисление:

private enum UserAction {RIGHT, LEFT, NONE}

UserAction action = UserAction.NONE;

И в обработчике, проверь какая кнопка нажата(A, D или никакая)

scene.setOnKeyPressed(new EventHandler<KeyEvent>(){
             @Override
             public void handle(KeyEvent event) {
                 switch(event.getCode()){
                     case A:
                         action = UserAction.LEFT;
                         break;
                     case D:
                         action = UserAction.RIGHT;
                         break;
                 }
             }
         });

Далее:

KeyFrame frame = new KeyFrame(Duration.seconds(0.016), 
        new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                switch(action){
                    case LEFT:
                            rect.setTranslateX(rect.getTranslateX() - 5);
                        break;
                    case RIGHT:
                            rect.setTranslateX(rect.getTranslateX() + 5 ); 
                        break;
                });

Вобщем примерно так.

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.