|
1
|
|
|
package example.animation; |
|
2
|
|
|
|
|
3
|
|
|
import org.gannacademy.cdf.graphics.geom.Ellipse; |
|
4
|
|
|
import org.gannacademy.cdf.graphics.ui.DrawingPanel; |
|
5
|
|
|
|
|
6
|
|
|
import java.awt.*; |
|
7
|
|
|
|
|
8
|
|
|
public class Bubble { |
|
9
|
|
|
private Ellipse e; |
|
10
|
|
|
private double dx, dy; |
|
11
|
|
|
public static final double DEFAULT_RADIUS = 10; |
|
12
|
|
|
|
|
13
|
|
|
public Bubble(DrawingPanel p) { |
|
14
|
|
|
if (Math.random() > 0.5) { |
|
15
|
|
|
e = new Ellipse((Math.random() > 0.5 ? -DEFAULT_RADIUS : p.getWidth()), Math.random() * p.getHeight(), DEFAULT_RADIUS, DEFAULT_RADIUS, p); |
|
16
|
|
|
} else { |
|
17
|
|
|
e = new Ellipse(Math.random() * p.getWidth(), (Math.random() > 0.5 ? -DEFAULT_RADIUS : p.getHeight()), DEFAULT_RADIUS, DEFAULT_RADIUS, p); |
|
18
|
|
|
} |
|
19
|
|
|
e.setFillColor(new Color((float) Math.random(), (float) Math.random(), (float) Math.random(), 1)); |
|
20
|
|
|
e.setStrokeColor(e.getFillColor().darker()); |
|
21
|
|
|
dx = Math.random() * (DEFAULT_RADIUS / 2) - (DEFAULT_RADIUS / 4); |
|
22
|
|
|
dy = Math.random() * (DEFAULT_RADIUS / 2) - (DEFAULT_RADIUS / 4); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public void step() { |
|
26
|
|
|
e.translate(dx, dy); |
|
27
|
|
|
if (e.getX() > e.getDrawingPanel().getWidth() || e.getX() < -e.getWidth()) { |
|
28
|
|
|
dx = -1 * dx; |
|
29
|
|
|
} |
|
30
|
|
|
if (e.getY() > e.getDrawingPanel().getHeight() || e.getY() < -e.getHeight()) { |
|
31
|
|
|
dy = -1 * dy; |
|
32
|
|
|
} |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public double getRadius() { |
|
36
|
|
|
return e.getWidth() / 2; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public boolean intersects(Bubble other) { |
|
40
|
|
|
return Math.hypot(e.getX() - other.e.getX(), e.getY() - other.e.getY()) < getRadius() + other.getRadius(); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public void absorb(Bubble other) { |
|
44
|
|
|
double a = Math.PI * (Math.pow(getRadius(), 2) + Math.pow(other.getRadius(), 2)), |
|
45
|
|
|
r = Math.sqrt(a / Math.PI), |
|
46
|
|
|
dr = (r - getRadius()) / 2, |
|
47
|
|
|
ratio = getRadius() / other.getRadius(); |
|
48
|
|
|
dx = (ratio * dx + other.dx) / ratio; |
|
49
|
|
|
dy = (ratio * dy + other.dy) / ratio; |
|
50
|
|
|
e.setFillColor(new Color( |
|
51
|
|
|
(int) Math.sqrt((Math.pow(e.getFillColor().getRed(), 2) + Math.pow(other.e.getFillColor().getRed(), 2)) / 2), |
|
52
|
|
|
(int) Math.sqrt((Math.pow(e.getFillColor().getGreen(), 2) + Math.pow(other.e.getFillColor().getGreen(), 2)) / 2), |
|
53
|
|
|
(int) Math.sqrt((Math.pow(e.getFillColor().getBlue(), 2) + Math.pow(other.e.getFillColor().getBlue(), 2)) / 2) |
|
54
|
|
|
)); |
|
55
|
|
|
e.setStrokeColor(e.getFillColor().darker()); |
|
56
|
|
|
e.setFrame(e.getX() - dr, e.getY() - dr, r * 2, r * 2); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
public void close() { |
|
60
|
|
|
e.removeFromDrawingPanel(); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|