p5.js中repeat未按指定次数执行,无限生成仙人掌问题咨询
问题原因与解决方案
核心问题
- p5.js无内置
repeat函数:你调用的repeat(1, cactus)不是p5.js原生API,这个函数不存在,无法按指定次数重复执行。 draw()的循环特性:draw()是p5.js的主渲染循环,默认每秒执行60次。哪怕repeat能正常工作,每一次draw循环都会触发一次repeat,导致每秒生成60次仙人掌,看起来就是无限生成。- 随机数函数错误:p5.js中生成随机数的函数是
random(),不是randomNumber()。
修正后的代码
方案一:在setup中生成(推荐,仅执行一次)
function setup() { createCanvas(windowWidth, windowHeight); const cactusCount = 1; // 指定生成数量 for (let i = 0; i < cactusCount; i++) { cactus(); } } // 无需draw函数,若不需要动画可直接删除 function draw() { // 若需要背景刷新可添加 background(255),静态生成无需此操作 } function cactus(){ const x = random(0, windowWidth); const y = random(0, windowHeight); line(x + 300, y + 275, x + 300, y + 250); // 主茎 line(x + 300, y + 258, x + 308, y + 258); // 右侧分支1 line(x + 308, y + 258, x + 308, y + 254); // 右侧分支2 line(x + 300, y + 265, x + 295, y + 265); // 左侧分支1 line(x + 295, y + 265, x + 295, y + 255); // 左侧分支2 }
方案二:在draw中添加执行开关
如果必须保留draw循环(比如后续要加动画),可以用标志变量控制仅生成一次:
let hasGeneratedCacti = false; function setup() { createCanvas(windowWidth, windowHeight); } function draw() { if (!hasGeneratedCacti) { const cactusCount = 1; for (let i = 0; i < cactusCount; i++) { cactus(); } hasGeneratedCacti = true; } } function cactus(){ const x = random(0, windowWidth); const y = random(0, windowHeight); line(x + 300, y + 275, x + 300, y + 250); // 主茎 line(x + 300, y + 258, x + 308, y + 258); // 右侧分支1 line(x + 308, y + 258, x + 308, y + 254); // 右侧分支2 line(x + 300, y + 265, x + 295, y + 265); // 左侧分支1 line(x + 295, y + 265, x + 295, y + 255); // 左侧分支2 }
说明
- 用
for循环替代不存在的repeat函数,直接控制生成次数。 - 将生成逻辑放在
setup中,利用其仅执行一次的特性,避免重复生成。 - 修正了随机数函数的调用,确保能正确生成随机位置。
内容的提问来源于stack exchange,提问作者Angelo
相关产品推荐
相关产品推荐

