-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBouncingBalls.java
More file actions
47 lines (42 loc) · 875 Bytes
/
BouncingBalls.java
File metadata and controls
47 lines (42 loc) · 875 Bytes
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
/*
* 模拟小球和墙发生弹性碰撞运动
*/
public class BouncingBalls {
public static void main(String[] args) {
int N = 1;
Ball[] balls = new Ball[N];
for(int i=0;i<N;i++)
balls[i] = new Ball();
while(true)
{
StdDraw.clear();
for (int i = 0; i < balls.length; i++) {
balls[i].move(0.5);
balls[i].draw();
}
StdDraw.show(50);
}
}
}
class Ball {
private double rx,ry;
private double vx,vy;
private final double radius = 0.01;
public Ball()
{
rx = 0.5;
ry = 0.5;
vx = 0.05;
vy = 0.02;
}
public void move(double dt) {
if ((rx + vx*dt < radius) || (rx + vx*dt > 1.0 - radius)) { vx = -vx; }
if ((ry + vy*dt < radius) || (ry + vy*dt > 1.0 - radius)) { vy = -vy; }
rx = rx + vx*dt;
ry = ry + vy*dt;
}
public void draw()
{
StdDraw.filledCircle(rx, ry, radius);
}
}