仅使用直线函数绘制分形树

问题描述 投票:0回答:2

我正在尝试弄清楚如何在不使用任何几何变换的情况下绘制分形树。

我已经想出了这段代码,但它无法正确旋转以用于进一步的分支。

void setup() {
  size(1000,1000);
  background(50);
  stroke(255);
}

void draw() {
  branch(100, width/2, height, 10, PI/2);
}

float angle = PI/6;
void branch(float size, float cx, float cy, int noi, float alpha) {

  if(noi != 0) { //Number of increments - noi
    float rx = cx + (cos(alpha) * size);
    float lx = cx - (cos(alpha) * size);
    float y = cy - (sin(alpha) * size);

    line(cx, cy, rx, y);
    line(cx, cy, lx, y);

    branch(size/2, rx, y, noi-1, alpha - angle);
    branch(size/2, lx, y, noi-1, alpha - angle);

  } else {
    return;

  }

}

我使用基本的三角转换来找到下一个右点和左点。我认为我没有使用正确的 alpha 值进行转换。

Right now i get this

Trying to draw this

algorithm recursion drawing processing fractals
2个回答
1
投票

我解决了问题。

void setup() {
  size(1000,1000);
  background(50);
  stroke(255);
}

void draw() {
  branch(100, width/2, height/2, 10, PI/2);
}

float angle = PI/6;
void branch(float size, float cx, float cy, int noi, float alpha) {

  if(noi != 0) { //Number of increments - noi
    float rx = cx + (cos(alpha) * size);
    //float lx = cx - (cos(alpha) * size);
    float y = cy - (sin(alpha) * size);

    line(cx, cy, rx, y);
    //line(cx, cy, rx, y);

    branch(size*0.66, rx, y, noi-1, alpha - angle);
    branch(size*0.66, rx, y, noi-1, alpha + angle);

  } else {
    return;

  }

}

1
投票

我相信你的问题在于角度管理以及你的假设

rx
lx
可以共享一个共同的
y
。这是我在 Python 海龟中的重做:

from turtle import Screen, Turtle
from math import pi as PI, sin as sine, cos as cosine

THETA = PI / 10  # spread between branches

def branch(size, cx, cy, noi, alpha):

    rx = cx + cosine(alpha - THETA) * size
    ry = cy - sine(alpha - THETA) * size

    line(cx, cy, rx, ry)

    lx = cx + cosine(alpha + THETA) * size
    ly = cy - sine(alpha + THETA) * size

    line(cx, cy, lx, ly)

    if noi != 0:  # Number of increments - noi

        branch(size * 0.9, rx, ry, noi - 1, alpha - THETA)
        branch(size * 0.9, lx, ly, noi - 1, alpha + THETA)

def line(x0, y0, x1, y1):

    turtle.penup()
    turtle.goto(x0, y0)
    turtle.pendown()
    turtle.goto(x1, y1)

screen = Screen()
screen.setup(1000, 1000)
screen.setworldcoordinates(-500, 500, 500, -500)  # invert Y axis

turtle = Turtle(visible=False)

line(0, 400, 0, 200)  # trunk

branch(100, 0, 200, 8, PI/2)

screen.exitonclick()

在此示例中,分支展开是一个常数,但我们仍然必须管理每个分支弯曲的角度:

© www.soinside.com 2019 - 2024. All rights reserved.