HIDE NAV

Pong 2020 - Pt.1

The basic structure of the Java FX applicaiton is built along with introducing a game loop based on javafx.animation.AnimationTimer and physics data for a ball.
The Pong Pt.1 video lesson documents the writing of this code and explains its structure.

Pong.java


package ceccs;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Pong extends Application {

    double gameHeight = 500;
    double gameWidth = 1000;
    double ballX = 490;
    double ballY = 50;
    double ballVx = .5;
    double ballVy = 0;
    double ballSize = 20;

    double ballAy = .1;

    @Override
    public void start(Stage primaryStage) throws Exception {

        Rectangle ball = new Rectangle(ballSize, ballSize);
        Pane pane = new Pane();
        pane.getChildren().add(ball);
        Scene scene = new Scene(pane);
        primaryStage.setScene(scene);
        primaryStage.setTitle("PONG");
        primaryStage.setResizable(false);
        primaryStage.setHeight(gameHeight);
        primaryStage.setWidth(gameWidth);
        primaryStage.show();

        ball.setX(ballX);
        ball.setY(ballY);

        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                // update pos.
                ballX = ballX + ballVx;
                ballVy = ballVy + ballAy;
                ballY = ballY + ballVy;

                //check boundaries
                if ((ballY >= gameHeight - ballSize) || (ballY < 0)){
                    ballY = ballY - ballVy;
                    ballVy = -ballVy;
                }
                if ((ballX >= gameWidth - ballSize) || (ballX < 0)){
                   ballX = ballX - ballVx;
                   ballVx = -ballVx;
                }

                //update graphics
                ball.setX(ballX);
                ball.setY(ballY);
            }
        };
        timer.start();
    }

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