Skip to content

Commit df220ed

Browse files
committed
recursive tree showing the use of objects
1 parent a01b5fb commit df220ed

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
ArrayList<Branch> tree = new ArrayList<Branch>();
2+
float angle;
3+
4+
void setup() {
5+
size(700, 700);
6+
7+
PVector begin = new PVector(0, 0);
8+
PVector end = new PVector(0, -190);
9+
Branch root = new Branch(begin, end);
10+
tree.add(root);
11+
12+
angle = PI / 4.0;
13+
}
14+
15+
void mousePressed() {
16+
for (int i = tree.size()-1; i >= 0; i = i - 1) {
17+
Branch currentBranch = tree.get(i);
18+
if (!currentBranch.finished) {
19+
Branch rightBranch = currentBranch.branch(angle);
20+
Branch leftBranch = currentBranch.branch(-angle);
21+
tree.add(rightBranch);
22+
tree.add(leftBranch);
23+
currentBranch.finished = true;
24+
}
25+
}
26+
}
27+
28+
void draw() {
29+
background(230);
30+
31+
pushMatrix();
32+
translate(width/2, height);
33+
for (Branch branch : tree) {
34+
branch.show();
35+
branch.swing(millis() / 100.0);
36+
}
37+
popMatrix();
38+
}
39+
40+
class Branch {
41+
PVector begin;
42+
PVector end;
43+
boolean finished;
44+
45+
Branch(PVector begin, PVector end) {
46+
this.begin = begin;
47+
this.end = end;
48+
}
49+
50+
Branch branch(float angle) {
51+
PVector dir = PVector.sub(this.end, this.begin);
52+
dir.rotate(angle);
53+
dir.mult(0.67);
54+
PVector newEnd = PVector.add(end, dir);
55+
Branch newBranch = new Branch(end, newEnd);
56+
return newBranch;
57+
}
58+
59+
void swing(float time) {
60+
float dist = map(PVector.dist(begin, end), 0, 190, 1, 0);
61+
end.x += (noise(end.x, time) - 0.5) * dist * 3;
62+
end.y += (noise(end.y, time) - 0.5) * dist * 3;
63+
}
64+
65+
void show() {
66+
stroke(0);
67+
line(begin.x, begin.y, end.x, end.y);
68+
}
69+
70+
}

0 commit comments

Comments
 (0)