我怎样才能使这个粒子代码 运行 成为我想要的呢?

How can I make this particle code run as I want it?

我正在尝试制作一个录音机可视化工具,其中的形状会与从屏幕左侧传递到右侧的小方块相互作用,使其看起来像是在录制语音笔记。出于某种原因,我无法让方块完全达到我想要的 space,所以我决定一次推出一个方块,当该方块到达屏幕上的某个部分时,另一个方块将从开始,这样他们就可以以我想要的速度移动并保持彼此之间的距离。

问题是当我让方块到达屏幕上的某个部分时,另一个方块根本没有添加,我尝试添加一个填充来改变颜色,看看会发生什么,但它只是改变了颜色当前方块的大小,仅此而已。

var nodes;

function setup() {
  createCanvas(windowWidth, windowHeight)

  nodes = new Particle();
}

function draw() {
  background(0);

  if (!nodes.deleteParticles()) {
    nodes.draw();
    nodes.update()
  }


}

function Particle() {
  this.x = windowWidth / 2;
  this.y = windowHeight / 2;
  this.width = 20;
  this.height = 50;

  this.particles = [];
  this.draw = function() {
    background(0)
    fill(255);

    this.particles.push(rect(this.x, this.y, this.width, this.height, 5))

    if (this.update()) {
      this.particles.push(rect(this.x, this.y, this.width, this.height, 5))
    }

  }
  this.update = function() {
    this.x -= 2;

    if (this.x < (windowWidth / 2) - 300) {
      return true;
    } else {
      return false;
    }
  }
  this.deleteParticles = function() {
    if (this.x < -20) {
      return true;
    } else {
      return false;
    }
  }

}
<!DOCTYPE html>
<html>

<head>
  <script src="lib/p5.min.js"></script>
  <script src="lib/p5.sound.js"></script>

  <script src="sketch.js"></script>

  <!--<link rel="stylesheet" type="text/css" href="style.css">-->
  <style>
    body {
      padding: 0;
      margin: 0;
    }
  </style>
</head>

<body>
</body>

</html>

我相信您从根本上误解了 rect() function works. The rect() function, and other shape drawing functions in p5.js, do not return a value. All shapes are draw in what is called "immediate mode" 的含义,即形状是立即绘制的,而不是可以操纵的持久对象。例如,如果你想移动一个矩形,你需要清除 canvas 并重新绘制矩形。

这是我能想到的对你的草图最明智的调整:

var nodes;

function setup() {
  createCanvas(windowWidth, windowHeight)

  nodes = new Particle();
}

function draw() {
  background(0);

  if (!nodes.deleteParticles()) {
    nodes.update();
  }
  
  nodes.draw();
}

function Particle() {
  this.x = windowWidth / 2;
  this.y = windowHeight / 2;
  this.width = 20;
  this.height = 50;

  this.particles = [];
  this.draw = function() {
    fill(255);

    for (const p of this.particles) { 
      rect(p.x, p.y, p.w, p.h, 5);
    }
  }
  
  this.update = function() {
    this.x -= 2;
    
    this.particles.push({
      x: this.x,
      y: this.y,
      w: this.width,
      h: this.height
    });

    if (this.x < (windowWidth / 2) - 300) {
      return true;
    } else {
      return false;
    }
  }
  
  this.deleteParticles = function() {
    if (this.x < -20) {
      return true;
    } else {
      return false;
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>