基本问题在标题中。我使用一个函数来定义一个带有特定参数集的p5.js实例。小品本身运行一个浏览器内的视频游戏。当一组事件中的任何一个在游戏中发生时,草图将被删除,结束游戏。给定草图的参数值数组,我使用for循环来构造使用数组的每个元素定义的草图。我预计在for循环的单次迭代中,定义的草图将在for循环进行之前完成(即运行到移除),并且定义并运行下一个草图。然而,实际发生的情况是,一旦定义了草图,循环就会继续并定义下一个草图。这将导致所有草图在浏览器中同时运行。
如何确保每个草图在下一个草图运行之前完成?我的猜测是,我可能需要将一些变量传递给适当调用noLoop()和Loop()的每个草图,但我不确定。下面是一个HTML文件形式的最小工作示例:
/* Function to define sketch with parameter 'a' */
function defineSketch(a) {
let sketch = function(p) {
let x = 100;
let y = 100;
p.setup = function() {
p.createCanvas(700, 410);
};
p.draw = function() {
p.background(0);
p.fill(255);
p.rect(x, y, a*50, a*50);
};
/* Remove sketch on mouse press */
p.mousePressed = function() {
p.remove();
};
};
}
/* Initialize sketch variable */
let trialSketch;
/* Array of parameters */
let param_seq = [0, 1, 2];
/* For loop to sequentially run sketches with different parameters */
for(let i = 0; i < param_seq.length; i++ ) {
trialSketch = defineSketch(param_seq[i]);
new p5(trialSketch);
}发布于 2021-03-02 03:03:03
用户Pr0tonX在
处理论坛
,解决方案是设置一个布尔值来检查草图是否正在运行,并在其上设置一个侦听器,如下所示:
// listened variable
// we set a listner which wiil be fired each time the value of bool is changed.
let sketchIsRunning = {
$: false,
listener: function(val) {},
set bool(val) {
this.$ = val;
this.listener(val);
},
get bool() {
return this.value;
},
registerListener: function(listener) {
this.listener = listener;
}
};
/* Function to define sketch with parameter 'a' */
function defineSketch(a) {
return function(p) {
let x = 100;
let y = 100;
p.setup = function() {
p.createCanvas(700, 410);
console.log('cool')
};
p.draw = function() {
p.background(0);
p.fill(255);
p.rect(x, y, a*50, a*50);
};
/* Remove sketch on mouse press */
p.mousePressed = function() {
p.remove();
sketchIsRunning.bool = !sketchIsRunning.bool
console.log('sketch is running ?', sketchIsRunning.bool)
};
};
}
/* Initialize sketch variable */
let trialSketch;
/* Array of parameters */
let param_seq = [0, 1, 2];
// we nest a call to the function itself to loop through the param.seq array
const instanceP5sketches = (i = 0) => {
sketchIsRunning.$ = !sketchIsRunning.$;
trialSketch = defineSketch(param_seq[i]);
new p5(trialSketch);
sketchIsRunning.registerListener(function(val) {
if (param_seq.length - 1 >= i){
instanceP5sketches(i+1);
} else {
console.log('No more sketches.')
}
});
}
instanceP5sketches();
https://stackoverflow.com/questions/66350972
复制相似问题