我怎样才能重写这段代码,让一个物体从 canvas 的顶部掉落,当它到达底部时,它会在顶部重置

how can i rewrite this code to make an object fall from top of canvas and when hits bottom it resets at top

我正在尝试实现一组对象,这些对象将从 canvas 的顶部随机落下,然后当它们到达 canvas 的底部时,它们会在顶部重生的 canvas。理想情况下,我想在将来更改此代码以使用将从 canvas 顶部掉落并在撞到 canvas 底部时爆炸但随后在顶部再次重生的精灵。

我有下面的代码可以在按下鼠标时运行,但我想重写这段代码,这样事件就会自动发生,而不需要按下鼠标来让物体掉落。

请参阅下面的代码。

var x, y;
var particle = [];

function setup() {
  createCanvas(720, 400);
  // Starts in the middle
  x = width / 2;
  y = height;
}

function draw() {
  background(0);
  if (mouseIsPressed){
  stroke(50);
  fill(100);
  ellipse(x, y, 24, 24);
  }
  x = x + 0;
  // Moving up at a constant speed
  y = y + 2;
  
  // Reset to the bottom
  if (y >= height) {
    y = 0;
  }
}

使用 mousePressed() 将新粒子添加到列表中。粒子被添加到当前鼠标位置 (mouseX, mouseY)。循环移动并绘制粒子:

var particles = [];

function setup() {
    createCanvas(720, 400);
}

function mousePressed() {
    particles.push([mouseX, mouseY]);
}

function draw() {
    background(0);
    stroke(50);
    for (let i=0; i < particles.length; i++) {
        particles[i][1] += 2;
        if (particles[i][1] > height) {
            particles[i][1] = 0;
        }
        fill(100);
        ellipse(particles[i][0], particles[i][1], 24, 24);
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

或者,您可以按时间间隔生成粒子。获取自从使用 millis(). The y-coordinate of a new particle is 0 and the x-coordinate is random():

开始草图以来的毫秒数(千分之一秒)

var particles = [];

function setup() {
    createCanvas(720, 400);
}

function mousePressed() {
    particles.push([mouseX, mouseY]);
}

function draw() {
    let max_no_of_particles = 40;
    let expected_no_of_praticles = min(max_no_of_particles, millis() / 100);
    if (particles.length < expected_no_of_praticles) {
        particles.push([random(12, width-12), 0]);
    }

    background(0);
    stroke(50);
    for (let i=0; i < particles.length; i++) {
        particles[i][1] += 2;
        if (particles[i][1] > height) {
            particles[i][1] = 0;
        }
        fill(100);
        ellipse(particles[i][0], particles[i][1], 24, 24);
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>