01
02
03
04
05
06
07
08
09
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
|
package algs11;
import stdlib.*;
/* ***********************************************************************
* Compilation: javac BouncingBall.java
* Execution: java BouncingBall
* Dependencies: StdDraw.java
*
* Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1).
*
* % java BouncingBall
*
*************************************************************************/
public class XBouncingBall {
public static void main(String[] args) {
// set the scale of the coordinate system
StdDraw.setXscale(-1.0, 1.0);
StdDraw.setYscale(-1.0, 1.0);
// initial values
double rx = 0.480, ry = 0.860; // position
double vx = 0.015, vy = 0.023; // velocity
double radius = 0.05; // radius
// main animation loop
while (true) {
// bounce off wall according to law of elastic collision
if (Math.abs(rx + vx) > 1.0 - radius) vx = -vx;
if (Math.abs(ry + vy) > 1.0 - radius) vy = -vy;
// update position
rx = rx + vx;
ry = ry + vy;
// clear the background
StdDraw.setPenColor(StdDraw.GRAY);
StdDraw.filledSquare(0, 0, 1.0);
// draw ball on the screen
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.filledCircle(rx, ry, radius);
// display and pause for 20 ms
StdDraw.show(20);
}
}
}
|