在我的代码中找不到错误,可能与我管理分支的方式有关 class

Cannot find the error in my code, possibly has to do with how I manage the Branch class

当我终于认为自己掌握了类的概念时,我尝试做一个简单的可视化来证实它。但是,我 运行 代码没有任何显示...可能只是一个简单的错误变量或其他东西,但它已经让我发疯了 2 个小时并且还在计数:

class Branch{
    constructor(orix, oriy, lifespan){
        this.orix = orix;
        this.oriy = oriy;
        this.x = orix;
        this.y = oriy;
        this.lifespan = lifespan;
    }
    update(){
        if(this.lifespan>0){
            this.nx = this.x + random(-1,1);
            this.ny = this.y + random(-1,0.1);
            lifespan--;
            stroke(256);
            strokeWeight(10);
            point(this.x,this.y);
            point(this.nx,this.ny);
            this.x = this.nx;
            this.y = this.ny;
            return this.x, this.y
        }
    }
}

class Tree{
    constructor(orx, ory){
        this.orx = orx;
        this.ory = ory;
        this.branches = [new Branch(this.orx, this.ory)];
    }
    update(){
        this.branches.forEach((branch)=>branch.update());
        if(this.branches.length<25){
            this.branches.forEach((branch)=>{if(random(10)>7.5){this.branches.push(new Branch(branch.update(),random(20)))}});
        }
    }
}
function setup() {
    createCanvas(windowWidth, windowHeight);
    giantree = new Tree(width/2,height);
}

function draw() {
    background(0);
    giantree.update();
}

你的draw()函数只调用giantree对象的update()函数,即classTreeTree 中的 update() 函数遍历所有 Branch 并调用 update().

Branch 中的所有绘图都由 if(this.lifespan>0){ 封装,但是 Tree 的构造函数中的行 this.branches = [new Branch(this.orx, this.ory)]; 没有设置 lifespan 变量。因此它是 undefined 并且代码永远不会执行。