使用setInterval, array.push(), for 循环,我希望每3 秒出现一个气泡,直到数组气泡的长度变为10。
但是,当我执行我的代码时,一次总共出现了10个气泡,并且console.log(array.length)表明长度正在增长,尽管我将它设置为小于10。我认为我的代码排列方式有问题,有人可以帮忙吗?
let bubbles = [];
var n = 10;
function setup() {
createCanvas(600, 400);
}
function addBubbles() {
for (let i = 0; i < n; i++) {
let x = random(50, 550);
let y = random(50, 350);
let r = random(10, 50);
let b = new Bubble(x, y, r);
setInterval(bubbles.push(b), 3000);
}
}
function draw() {
background(0);
addBubbles();
for (let i = 0; i < n; i++) {
bubbles[i].show();
bubbles[i].move();
}
}
class Bubble {
constructor(_x, _y, _r, _c) {
this.x = _x;
this.y = _y;
this.r = _r;
this.c = _c;
}
move() {
this.x = this.x + random(-5, 5);
this.y = this.y + random(-5, 5);
}
show() {
stroke(255);
noFill();
strokeWeight(4);
ellipse(this.x, this.y, this.r * 2);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
一只萌萌小番薯
素胚勾勒不出你
慕慕森
随时随地看视频慕课网APP
相关分类