# 遞迴樹：branch 自己呼叫自己

正式網址：https://newmediaart.course.monolab.world/snippets/recursive-branch

一個 branch(len, depth, angle) 函式，畫一段樹枝再往左右各長兩根短一點的，depth 減到 0 就停；範例從畫面底部長一棵，滑鼠左右移動改分枝角度。

- **分類**：自然的演算法
- **行數**：33 行（p5.js 1.x／2.x）
- **在哪一堂用到**：[第 3 堂](https://newmediaart.course.monolab.world/lesson/03)

複製 branch() 進自己的 sketch，在 draw() 裡先 translate() 到樹根，再呼叫 branch(長度, 層數, 角度)；層數每加 1，枝條數量翻倍，電腦跑不動就調小。

```js
// 遞迴樹：一根樹枝畫完，在尖端分出左右兩根更短的，一直分到 depth 歸零
function setup() {
  createCanvas(640, 420);
}

function draw() {
  background(18, 25, 40);
  let angle = map(mouseX, 0, width, 0, HALF_PI); // 滑鼠 x 控制分枝張開多大
  translate(width / 2, height); // 原點移到畫面底部中間
  branch(90, 9, angle);
}

// len 這根枝的長度，depth 還要再分幾層，angle 左右各轉多少（弧度）
function branch(len, depth, angle) {
  if (depth === 0) return; // 停止條件：沒有它會無限呼叫下去
  stroke(190, 150, 100);
  strokeWeight(depth * 0.9);
  line(0, 0, 0, -len);
  translate(0, -len); // 走到枝尖
  if (depth === 1) {
    noStroke();
    fill(255, 150, 190);
    circle(0, 0, 8); // 最末端開一朵小花
  }
  push();
  rotate(angle);
  branch(len * 0.7, depth - 1, angle); // 右邊那根
  pop();
  push();
  rotate(-angle);
  branch(len * 0.7, depth - 1, angle); // 左邊那根
  pop();
}
```

## 同類常用指令・自然的演算法

- [海龜繪圖：照字串畫線](https://newmediaart.course.monolab.world/snippets/turtle-draw)
- [L-System：規則換字長出一棵樹](https://newmediaart.course.monolab.world/snippets/lsystem-grow)
- [Noise 年輪：接得起來的不規則圈](https://newmediaart.course.monolab.world/snippets/noise-ring)
- [Boid 三條規則：分離、對齊、聚合](https://newmediaart.course.monolab.world/snippets/boid-rules)

[回到全部常用指令](https://newmediaart.course.monolab.world/snippets)

[到 Hahow 報名](https://hahow.in/cr/creative-code)。價格與優惠以 Hahow 頁面為準。
