p5.js 形状循环错误(全部卡在一点)

p5.js shape loop error (all stuck at one point)

我几乎让这个 p5.js 'artwork' 工作了。但我不确定为什么他们都停留在一个点上。 我以 class 格式编写它们,并检查了代码但找不到导致它的任何错误。谢谢

没有太多细节要补充抱歉没有太多细节要补充抱歉没有太多细节要补充抱歉没有太多细节要补充抱歉没有太多细节要补充抱歉没有太多细节要补充抱歉没有太多细节要补充抱歉没有太多细节要添加抱歉没有太多细节要添加抱歉

cubic = [];
function setup(){
  createCanvas(windowWidth, windowHeight, WEBGL);
  back = color(22,22,22);
  
  for (let i = 0; i < 5; i++) {
    let looper = map(i, 0, 4, 100, width - 100);
    cubic.push(new class_Cube(looper, 0) );
  }

}

function draw(){
  background(back);
 for (let j = 0; j < cubic.length; j++) {
    cubic[j].update();
  }
 }

function mouseClicked() {
  cubic = [];
  for (let i = 0; i < 5; i++) {
    let looper = map(i, 0, 4, 100, width - 100);
    cubic.push(new class_Cube(looper, height/2) );
  }
}

class class_Cube {
  constructor(x,y) {
    this.x = x;
    this.y = y;
    //cube values
    this.size = 50;
    this.stroke = 255;
    //rotation
    this.randX = random(0,360);
    this.randY = random(0,360);
  }
  
  update() {
    this.cubes();
    this.rotate();
  }
  
  cubes() {
    push();
    noFill();
    stroke(this.stroke);
    box(this.size);
    pop();
    }
  
  rotate() {
    rotateX(this.randX);
    rotateY(this.randY);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

您必须通过 translate() 设置翻译才能将每个立方体放在其位置。
注意,像 translate()rotate() define a matrix and multiply the current matrix by the new matrix. Hence you have to store the current matrix by push(), before you change the model matrix of the cube. After you have drawn the cube, you have to restore the matrix by pop():

这样的操作
class class_Cube {
    // [...]

    update() {
        push()

        translate(this.x, this.y)
        this.rotate(); 

        this.cubes();

        pop();
    }

    // [...]
}

看例子:

cubic = [];
function setup(){
  createCanvas(windowWidth, windowHeight, WEBGL);
  back = color(22,22,22);
  
  for (let i = 0; i < 5; i++) {
    let looper = map(i, 0, 4, -width/2 + 100, width/2 - 100);
    cubic.push(new class_Cube(looper, 0) );
  }

}

function draw(){
  background(back);
 for (let j = 0; j < cubic.length; j++) {
    cubic[j].update();
  }
 }

function mouseClicked() {
  cubic = [];
  for (let i = 0; i < 5; i++) {
    let looper = map(i, 0, 4, 0, width-10);
    cubic.push(new class_Cube(looper, height/2) );
  }
}

class class_Cube {
  constructor(x,y) {
    this.x = x;
    this.y = y;
    //cube values
    this.size = 50;
    this.stroke = 255;
    //rotation
    this.randX = random(0,360);
    this.randY = random(0,360);
  }
  
  update() {
    push()
    translate(this.x, this.y)
    this.rotate(); 
    this.cubes();
    pop();
  }
  
  cubes() {
    push();
    noFill();
    stroke(this.stroke);
    box(this.size);
    pop();
    }
  
  rotate() {
    rotateX(this.randX);
    rotateY(this.randY);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>