JavaFX Basic Physics Demonstration
A basic physics demo in Java FX - a single bouncing ball.
PhysDemo.java
package ceccs;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class PhysDemo extends Application {
AnimationTimer aTimer;
Pane physPane;
Circle ball;
double ballX,ballY, ballVx, ballVy, ballAy, ballSize;
double physW = 1000;
double physH = 600;
@Override
public void start(Stage primaryStage) throws Exception {
ballSize = 20;
ball = new Circle(ballSize, Color.YELLOW);
physPane = new Pane(ball);
//set init. phys.
ballX = physW/2;
ballY = physH/2;
ballAy = 1;
ballVx = 3;
ballVy = 2;
updateBallGfx();
//timer
setupTimer();
aTimer.start();
Rectangle bgRect = new Rectangle(physW,physH,new Color(.2,.2,.2,1));
StackPane root = new StackPane(bgRect,physPane);
Scene scene = new Scene(root,physW, physH);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args){
launch(args);
}
void setupTimer(){
aTimer = new AnimationTimer() {
@Override
public void handle(long now) {
ballVy += ballAy;
ballX += ballVx;
ballY += ballVy;
if (ballX >= physW-ballSize || ballX < ballSize) {
ballX -= ballVx; // declip: reverse prev. step
ballVx = -ballVx; // reflect
}
if (ballY >= physH-ballSize || ballY < ballSize) {
ballY -= ballVy;
ballVy = -1* ballVy;
}
updateBallGfx();
}
};
}
void updateBallGfx(){
ball.setCenterX(ballX);
ball.setCenterY(ballY);
}
}