JavaFX Basic Physics Scale-Up
A basic physics demo in Java FX - uses a phsyics object class and ArrayList to scale up physics.
PhysBall.java
package ceccs;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
public class PhysBall extends Circle {
PhysDemoScaleUp app;
private double x, y, vx, vy, ax, ay, radius;
static double gravity = 1;
PhysBall(double ballSize, Color color, double x, double y, PhysDemoScaleUp app){
super(x,y,ballSize,color);
this.app = app;
radius = ballSize;
this.x = x;
this.y = y;
vx = 0;
vy = 0;
ax = 0;
ay = 0;
app.physPane.getChildren().add(this);
}
void updatePhysics(){
vx += ax;
x += vx;
vy += ay;
y += vy;
//collision with sides
if (x < 0 || x > app.physW) {
x -= vx; // take away the last step
vx = -vx; // reflect x velocity
}
if (y < 0 || y > app.physH) {
y -= vy; // take away the last step
vy = -vy; // reflect x velocity
}
}
void updateGraphics(){
setCenterX(x);
setCenterY(y);
}
void setVelocity(double vx, double vy){
this.vx = vx;
this.vy = vy;
}
void enableGravity(){
this.ay = gravity;
}
}
PhysDemoScaleUp.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.Rectangle;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Random;
public class PhysDemoScaleUp extends Application {
AnimationTimer timer;
Pane physPane;
double physW = 1000;
double physH = 600;
Stage stage;
ArrayList<PhysBall> balls;
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
stage = primaryStage;
setupLayout();
balls = new ArrayList();
//Random randy = new Random();
for(int i = 0; i < 1000; i++){
double rx = Math.random()*physW;
double ry = Math.random()*physH;
PhysBall b = new PhysBall(5, new Color( 0, Math.random(),Math.random(), .35 ), rx,ry, this );
b.setVelocity(Math.random()-.5, Math.random()-.5);
b.enableGravity();
balls.add(b);
}
setupTimer();
timer.start();
primaryStage.setTitle("Physics-ScaleUp-Tester");
primaryStage.show();
}
void setupLayout(){
Rectangle bgRect = new Rectangle(physW,physH,new Color(.2,.2,.2,1));
physPane = new Pane();
StackPane root = new StackPane(bgRect, physPane);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setResizable(false);
}
void setupTimer(){
timer = new AnimationTimer() {
@Override
public void handle(long now) {
for(int i = 0; i < balls.size(); i++){
balls.get(i).updatePhysics();
balls.get(i).updateGraphics();
}
}
};
}
}