-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjumping_ball.java
391 lines (326 loc) · 15 KB
/
jumping_ball.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package com.example.ColorSwitchGame;
import static java.lang.Math.PI;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static javafx.scene.paint.Color.BLACK;
import static javafx.scene.paint.Color.BLUE;
import static javafx.scene.paint.Color.BROWN;
import static javafx.scene.paint.Color.GREEN;
import static javafx.scene.paint.Color.PINK;
import static javafx.scene.paint.Color.RED;
import static javafx.scene.paint.Color.YELLOW;
import java.util.ListIterator;
import java.util.Random;
import java.util.concurrent.Callable;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.LongProperty;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.beans.property.ReadOnlyDoubleWrapper;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
public class jumping_ball extends Application {
private ObservableList<Ball> balls = FXCollections.observableArrayList();
private static final int NUM_BALLS = 400;
private static final double MIN_RADIUS = 5 ;
private static final double MAX_RADIUS = 15 ;
private static final double MIN_SPEED = 50 ;
private static final double MAX_SPEED = 250 ;
private static final Color[] COLORS = new Color[] { RED, YELLOW, GREEN,
BROWN, BLUE, PINK, BLACK };
private final FrameStats frameStats = new FrameStats() ;
@Override
public void start(Stage primaryStage) {
final Pane ballContainer = new Pane();
constrainBallsOnResize(ballContainer);
ballContainer.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getClickCount() == 2) {
balls.clear();
createBalls(NUM_BALLS, MIN_RADIUS, MAX_RADIUS, MIN_SPEED, MAX_SPEED, ballContainer.getWidth()/2, ballContainer.getHeight()/2);
}
}
});
balls.addListener(new ListChangeListener<Ball>() {
@Override
public void onChanged(Change<? extends Ball> change) {
while (change.next()) {
for (Ball b : change.getAddedSubList()) {
ballContainer.getChildren().add(b.getView());
}
for (Ball b : change.getRemoved()) {
ballContainer.getChildren().remove(b.getView());
}
}
}
});
createBalls(NUM_BALLS, MIN_RADIUS, MAX_RADIUS, MIN_SPEED, MAX_SPEED, 400, 300);
final BorderPane root = new BorderPane();
final Label stats = new Label() ;
stats.textProperty().bind(frameStats.textProperty());
root.setCenter(ballContainer);
root.setBottom(stats);
final Scene scene = new Scene(root, 800, 800);
primaryStage.setScene(scene);
primaryStage.show();
startAnimation(ballContainer);
}
private void startAnimation(final Pane ballContainer) {
final LongProperty lastUpdateTime = new SimpleLongProperty(0);
final AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long timestamp) {
if (lastUpdateTime.get() > 0) {
long elapsedTime = timestamp - lastUpdateTime.get();
checkCollisions(ballContainer.getWidth(), ballContainer.getHeight());
updateWorld(elapsedTime);
frameStats.addFrame(elapsedTime);
}
lastUpdateTime.set(timestamp);
}
};
timer.start();
}
private void updateWorld(long elapsedTime) {
double elapsedSeconds = elapsedTime / 1_000_000_000.0;
for (Ball b : balls) {
b.setCenterX(b.getCenterX() + elapsedSeconds * b.getXVelocity());
b.setCenterY(b.getCenterY() + elapsedSeconds * b.getYVelocity());
}
}
private void checkCollisions(double maxX, double maxY) {
for (ListIterator<Ball> slowIt = balls.listIterator(); slowIt.hasNext();) {
Ball b1 = slowIt.next();
// check wall collisions:
double xVel = b1.getXVelocity();
double yVel = b1.getYVelocity();
if ((b1.getCenterX() - b1.getRadius() <= 0 && xVel < 0)
|| (b1.getCenterX() + b1.getRadius() >= maxX && xVel > 0)) {
b1.setXVelocity(-xVel);
}
if ((b1.getCenterY() - b1.getRadius() <= 0 && yVel < 0)
|| (b1.getCenterY() + b1.getRadius() >= maxY && yVel > 0)) {
b1.setYVelocity(-yVel);
}
for (ListIterator<Ball> fastIt = balls.listIterator(slowIt.nextIndex()); fastIt.hasNext();) {
Ball b2 = fastIt.next();
// performance hack: both colliding(...) and bounce(...) need deltaX and deltaY, so compute them once here:
final double deltaX = b2.getCenterX() - b1.getCenterX() ;
final double deltaY = b2.getCenterY() - b1.getCenterY() ;
if (colliding(b1, b2, deltaX, deltaY)) {
bounce(b1, b2, deltaX, deltaY);
}
}
}
}
public boolean colliding(final Ball b1, final Ball b2, final double deltaX, final double deltaY) {
// square of distance between balls is s^2 = (x2-x1)^2 + (y2-y1)^2
// balls are "overlapping" if s^2 < (r1 + r2)^2
// We also check that distance is decreasing, i.e.
// d/dt(s^2) < 0:
// 2(x2-x1)(x2'-x1') + 2(y2-y1)(y2'-y1') < 0
final double radiusSum = b1.getRadius() + b2.getRadius();
if (deltaX * deltaX + deltaY * deltaY <= radiusSum * radiusSum) {
if ( deltaX * (b2.getXVelocity() - b1.getXVelocity())
+ deltaY * (b2.getYVelocity() - b1.getYVelocity()) < 0) {
return true;
}
}
return false;
}
private void bounce(final Ball b1, final Ball b2, final double deltaX, final double deltaY) {
final double distance = sqrt(deltaX * deltaX + deltaY * deltaY) ;
final double unitContactX = deltaX / distance ;
final double unitContactY = deltaY / distance ;
final double xVelocity1 = b1.getXVelocity();
final double yVelocity1 = b1.getYVelocity();
final double xVelocity2 = b2.getXVelocity();
final double yVelocity2 = b2.getYVelocity();
final double u1 = xVelocity1 * unitContactX + yVelocity1 * unitContactY ; // velocity of ball 1 parallel to contact vector
final double u2 = xVelocity2 * unitContactX + yVelocity2 * unitContactY ; // same for ball 2
final double massSum = b1.getMass() + b2.getMass() ;
final double massDiff = b1.getMass() - b2.getMass() ;
final double v1 = ( 2*b2.getMass()*u2 + u1 * massDiff ) / massSum ; // These equations are derived for one-dimensional collision by
final double v2 = ( 2*b1.getMass()*u1 - u2 * massDiff ) / massSum ; // solving equations for conservation of momentum and conservation of energy
final double u1PerpX = xVelocity1 - u1 * unitContactX ; // Components of ball 1 velocity in direction perpendicular
final double u1PerpY = yVelocity1 - u1 * unitContactY ; // to contact vector. This doesn't change with collision
final double u2PerpX = xVelocity2 - u2 * unitContactX ; // Same for ball 2....
final double u2PerpY = yVelocity2 - u2 * unitContactY ;
b1.setXVelocity(v1 * unitContactX + u1PerpX);
b1.setYVelocity(v1 * unitContactY + u1PerpY);
b2.setXVelocity(v2 * unitContactX + u2PerpX);
b2.setYVelocity(v2 * unitContactY + u2PerpY);
}
private void createBalls(int numBalls, double minRadius, double maxRadius, double minSpeed, double maxSpeed, double initialX, double initialY) {
final Random rng = new Random();
for (int i = 0; i < numBalls; i++) {
double radius = minRadius + (maxRadius-minRadius) * rng.nextDouble();
double mass = Math.pow((radius / 40), 3);
final double speed = minSpeed + (maxSpeed - minSpeed) * rng.nextDouble();
final double angle = 2 * PI * rng.nextDouble();
Ball ball = new Ball(initialX, initialY, radius, speed*cos(angle),
speed*sin(angle), mass);
ball.getView().setFill(COLORS[i % COLORS.length]);
// ball.getView().setFill(i==0 ? RED : TRANSPARENT);
balls.add(ball);
}
}
private void constrainBallsOnResize(final Pane ballContainer) {
ballContainer.widthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
if (newValue.doubleValue() < oldValue.doubleValue()) {
for (Ball b : balls) {
double max = newValue.doubleValue() - b.getRadius();
if (b.getCenterX() > max) {
b.setCenterX(max);
}
}
}
}
});
ballContainer.heightProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
if (newValue.doubleValue() < oldValue.doubleValue()) {
for (Ball b : balls) {
double max = newValue.doubleValue() - b.getRadius();
if (b.getCenterY() > max) {
b.setCenterY(max);
}
}
}
}
});
}
private static class Ball {
private final DoubleProperty xVelocity ; // pixels per second
private final DoubleProperty yVelocity ;
private final ReadOnlyDoubleWrapper speed ;
private final double mass; // arbitrary units
private final double radius; // pixels
private final Circle view;
public Ball(double centerX, double centerY, double radius,
double xVelocity, double yVelocity, double mass) {
this.view = new Circle(centerX, centerY, radius);
this.xVelocity = new SimpleDoubleProperty(this, "xVelocity", xVelocity);
this.yVelocity = new SimpleDoubleProperty(this, "yVelocity", yVelocity);
this.speed = new ReadOnlyDoubleWrapper(this, "speed");
speed.bind(Bindings.createDoubleBinding(new Callable<Double>() {
@Override
public Double call() throws Exception {
final double xVel = getXVelocity();
final double yVel = getYVelocity();
return sqrt(xVel * xVel + yVel * yVel);
}
}, this.xVelocity, this.yVelocity));
this.mass = mass;
this.radius = radius;
view.setRadius(radius);
}
public double getMass() {
return mass;
}
public double getRadius() {
return radius;
}
public final double getXVelocity() {
return xVelocity.get();
}
public final void setXVelocity(double xVelocity) {
this.xVelocity.set(xVelocity);
}
public final DoubleProperty xVelocityProperty() {
return xVelocity;
}
public final double getYVelocity() {
return yVelocity.get();
}
public final void setYVelocity(double yVelocity) {
this.yVelocity.set(yVelocity);
}
public final DoubleProperty yVelocityProperty() {
return yVelocity;
}
public final double getSpeed() {
return speed.get();
}
public final ReadOnlyDoubleProperty speedProperty() {
return speed.getReadOnlyProperty() ;
}
public final double getCenterX() {
return view.getCenterX();
}
public final void setCenterX(double centerX) {
view.setCenterX(centerX);
}
public final DoubleProperty centerXProperty() {
return view.centerXProperty();
}
public final double getCenterY() {
return view.getCenterY();
}
public final void setCenterY(double centerY) {
view.setCenterY(centerY);
}
public final DoubleProperty centerYProperty() {
return view.centerYProperty();
}
public Shape getView() {
return view;
}
}
private static class FrameStats {
private long frameCount ;
private double meanFrameInterval ; // millis
private final ReadOnlyStringWrapper text = new ReadOnlyStringWrapper(this, "text", "Frame count: 0 Average frame interval: N/A");
public long getFrameCount() {
return frameCount;
}
public double getMeanFrameInterval() {
return meanFrameInterval;
}
public void addFrame(long frameDurationNanos) {
meanFrameInterval = (meanFrameInterval * frameCount + frameDurationNanos / 1_000_000.0) / (frameCount + 1) ;
frameCount++ ;
text.set(toString());
}
public String getText() {
return text.get();
}
public ReadOnlyStringProperty textProperty() {
return text.getReadOnlyProperty() ;
}
@Override
public String toString() {
return String.format("Frame count: %,d Average frame interval: %.3f milliseconds", getFrameCount(), getMeanFrameInterval());
}
}
public static void main(String[] args) {
launch(args);
}
}