用线函数绘制分形树

2024-04-26 13:30:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何在不使用任何几何变换的情况下绘制分形树。你知道吗

我已经想出了这个代码,但它不能正确地为进一步的分支旋转。你知道吗

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


Tags: alphabranchsizelinepicosfloatrx
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()

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

enter image description here

我解决了这个问题。你知道吗

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;

  }

}

相关问题 更多 >