如何让对象以 p5.js 中随时间减少的间隔出现

How can I make objects appear at intervals that decrease over time in p5.js

我想让一个数组中的一些元素出现在不同的时间,时间会随着时间的推移而减少(所以元素会出现得越来越快)。我曾尝试使用 setTimeout 和 setInterval 但没有成功,我认为这是因为我正在遍历数组。

你不能通过间隔来实现。然而,递归超时是可能的。例如,假设时间减少了 2 倍:

const initialDuration = 10000;

function someAnimation(duration) {
    // Your animation code here...

    setTimeout(() => someAnimation(duration / 2), duration);
}

someAnimation(initialDuration);

这是一个简单的 p5.js 示例,希望能为您指明正确的方向。

我在初始化时为每个对象调用 setTimeout 函数。超时延迟增加一个值 incrementor,每次迭代都会减少。

let circles = [];
let count = 100;
let incrementor = 500;
let delay = 500;

function setup() {
  createCanvas(400, 400);
  
  for (let i = 0; i < count; i++) {
    let circle = {
      x: random(width),
      y: random(height),
      show: false,
      
    }
    incrementor *= 0.9;
    delay += incrementor;
    setTimeout(() => circle.show = true, delay);
    circles.push(circle);
    
  }
}

function draw() {
  background(220);
  noStroke()
  fill(0, 128, 128);
  for (let circle of circles) {
    if (circle.show) {
      ellipse(circle.x, circle.y, 10, 10);
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>