p5.j​​s 使用 setInterval、array.push()、for 循环创建动画时出现

使用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>


一只萌萌小番薯
浏览 248回答 2
2回答

素胚勾勒不出你

我可以看到你已经准确地实现了 setInterval() 方法,并且根据你组织代码的方式,你得到的结果是相当公平的,因为你的 addBubbles() 方法是在 FOR 循环有机会执行之前执行的开始,这就是为什么你会一次得到 10 个气泡。我建议你像这样在循环中抛出 addBubbles() 方法:&nbsp;for (let i = 0; i < n; i++) {&nbsp; &nbsp; addBubbles();&nbsp; }这样,您的 addBubbles() 方法将随着增量每 3000 毫秒执行一次。

慕慕森

您的代码中存在一些问题。问题 1: 每次绘制画布时,都会开始 10 个间隔。这些间隔中的每一个都将每 3 秒运行一次函数。这会很快(并且成倍地)给你很多泡沫。要每 3 秒添加 1 个气泡,您只需启动 1 个间隔。您可以在您的setup函数中执行此操作,因为它只被调用一次。您可以在addBubble函数中添加一个检查,一旦您有一定数量的气泡,它将取消间隔。问题 2: 在调用setInterval().您已bubbles.push(b)作为每 3 秒运行一次的函数传递。bubbles.push(b)不返回函数类型。bubbles.push我们将传递一个向数组添加气泡的函数,而不是传递 的返回值。问题 3:n在绘制画布时,您 只需要迭代(10) 个气泡。相反,您需要遍历所有这些。let bubbles = [];let maxBubbles = 10;let interval;funtion setup() {&nbsp; createCanvas(600, 400);&nbsp; interval = setInterval(addBubble, 3000);}function addBubble() {&nbsp; let x = random(50, 550);&nbsp; let y = random(50, 350);&nbsp; let r = random(10, 50);&nbsp; let b = new Bubble(x, y, r);&nbsp; bubbles.push(b);&nbsp; if (bubbles.length >= maxBubbles) {&nbsp; &nbsp; clearInterval(interval);&nbsp; }}function draw() {&nbsp; background(0);&nbsp; for (let bubble of bubbles) {&nbsp; &nbsp; bubble.show();&nbsp; &nbsp; bubble.move();&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript