【问题标题】:Drawing fractal trees only using line function仅使用线函数绘制分形树
【发布时间】:2019-05-16 15:50:55
【问题描述】:

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

我想出了这段代码,但它不能正确旋转以进行更多分支。

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

【问题讨论】:

  • 请添加您尝试创建的树类型、您得到的结果以及您期望的结果。

标签: python recursion drawing processing fractals


【解决方案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;

  }

}

【讨论】:

    【解决方案2】:

    我相信您的问题在于角度管理,并且您假设 rxlx 可以共享一个共同的 y。这是我在 Python turtle 中的返工:

    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()
    

    在这个例子中,分支展开是一个常数,但我们仍然需要管理每个分支弯曲的角度:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 2014-03-05
      相关资源
      最近更新 更多