我如何 运行 与 p5js 绘制循环并行编码?

How can I run code in parallel to p5js draw loop?

我正在尝试 运行 像编码火车中的 this one 这样的植绒模拟。

我想我可以通过 运行将我的代码放在与 p5 绘制循环并行的单独异步循环中来加快速度。我的模拟代码可以更新 boids 的位置,p5 代码可以绘制 boids。这样,绘制循环就不必因模拟代码而减慢,我的代码也不必因绘图而减慢。

A​​) 你认为这实际上会加速模拟或者至少允许 p5 以更高的帧速率绘制吗?和 B) 你如何 运行 这两个并行?

感谢您的帮助!

Do you think that would actually speed up the simulation?

这取决于,如果模拟代码非常昂贵,可能是。

How would you run the two in parallel?

使用带有无限循环的asynchronous function。例如:

function setup() {
    // ...
    simulationLoop();
}

function draw() {
    // ...
}

async function simulationLoop() {

    while (true) {
        // calculate simulation

        await sleep(1); 
    }
}

function sleep(ms) {
    return new Promise(resolve => {setTimeout(() => { resolve(true); }, 1); });
}

请参阅 How to “pause” during merge sort to visualize JS p5js,其中此技术用于可视化合并排序算法。

甚至可以通过使用setTimeout来创建一个固定频率的循环。例如:

var count = 0;

function setup() {
    createCanvas(500, 200);
    simulationLoop();
}

function draw() {
    background(0);
    stroke(0);
    fill(255);
    textSize(50);
    text(str(count), 10, 60);
}

async function simulationLoop() {

    while (true) { 
        await new Promise(resolve => {
            setTimeout(() => {
                resolve(true);
                simulation();
            }, 1000); 
        });
    }
}

function simulation() {
    count ++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>


另一个简单的选择是使用 requestAnimationFrame():

var count = 0;

function setup() {
    createCanvas(500, 250);
    requestAnimationFrame(simulation);
}

function draw() {
    background(0);
    stroke(0);
    fill(255);
    textSize(50);
    text(str(count), 10, 60);
}

function simulation(deltaTime) {
    
    count = Math.trunc(deltaTime / 1000);
    
    requestAnimationFrame(simulation);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>