Reputation: 1054
I'm trying to run a flocking simulation like this one from the coding train.
I was thinking I might be able to speed things up by running my code in a separate asynchronous loop in parallel to the p5 draw loop. My simulation code could update the positions of the boids and the p5 code could draw the boids. That way, the draw loop wouldn't have to be slowed down by the simulation code and my code wouldn't have to be slowed down by the drawing.
A) Do you think that would actually speed up the simulation or at least allow p5 to draw at a higher frame rate? and B) How would you run the two in parallel?
Thanks for your help!
Upvotes: 3
Views: 1754
Reputation: 210909
Do you think that would actually speed up the simulation?
That depends on, if the simulation code is very expensive the probably yes.
How would you run the two in parallel?
Use an asynchronous function with an endless loop. e.g:
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); });
}
See How to “pause” during merge sort to visualize JS p5js where this technique is used to visualize the merge sort algorithm.
It is even possibly to create a loop with a fixed frequency by the use of setTimeout
. e.g.:
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>
Another simple option is to use 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>
Upvotes: 2