我试图使用构造函数获得一些练习,但我想出了一个关于random()函数的错误:
12:未捕获的ReferenceError:未定义random "%c您是否只是尝试使用p5.js的random()函数?如果是这样,您可能希望将其移动到草图的setup()函数中。\ n \ n有关详细信息,请参阅:github.com/processing/p5.js/wiki/Frequently-Asked-Questions#why-斜面-I-分配变量-使用-P5-函数和变量先于设置"
我可以只在setup()函数中使用此函数吗?我以前不认为我曾遇到过这个问题。是否有使用类似逻辑的解决方案?
var circles = function(x,y,d,xSpeed,ySpeed) {
this.x = x;
this.y = y;
this.d = d;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
}
var circle1 = new circles(random(width),random(height), random(30,55),random(3,19),random(3,19));
var circle2 = new circles(random(width),random(height), random(30,55), random(3,19),random(3,19));
var circle3 = new circles(random(width),random(height), random(30,55), random(3,19),random(3,19));
var circle4 = new circles(random(width),random(height), random(30,55), random(3,19),random(3,19));
var circle5 = new circles(random(width),random(height), random(30,55), random(3,19),random(3,19));
var circle6 = new circles(random(width),random(height), random(30,55), random(3,19),random(3,19));
function setup() {
createCanvas(900,900);
}
function draw() {
background(0);
fill(255,255,0);
ellipse(circle1.x,circle1.y,circle1.d,circle1.d);
}
function moveCircles() {
}
答案 0 :(得分:1)
从技术上讲,您可以使用按需全局模式在setup()
函数之外使用此函数,正如文档所述。但是,如果您没有使用任何其他第三方库,建议仅在setup()
函数内使用此函数。
p5功能
new p5(); // you need to call this fn first
var circle1 = new circles(random(width),random(height), random(30,55),random(3,19),random(3,19));
var circle2 = new circles(random(width),random(height), random(30,55), random(3,19),random(3,19));
var circle3 = new circles(random(width),random(height), random(30,55), random(3,19),random(3,19));
var circle4 = new circles(random(width),random(height), random(30,55), random(3,19),random(3,19));
var circle5 = new circles(random(width),random(height), random(30,55), random(3,19),random(3,19));
var circle6 = new circles(random(width),random(height), random(30,55), random(3,19),random(3,19));
p5函数insde setup
var circle1, circle2, circle3, circle4, circle5, circle6;
function setup() {
createCanvas(900, 900);
circle1 = new circles(random(width), random(height), random(30, 55), random(3, 19), random(3, 19));
circle2 = new circles(random(width), random(height), random(30, 55), random(3, 19), random(3, 19));
circle3 = new circles(random(width), random(height), random(30, 55), random(3, 19), random(3, 19));
circle4 = new circles(random(width), random(height), random(30, 55), random(3, 19), random(3, 19));
circle6 = new circles(random(width), random(height), random(30, 55), random(3, 19), random(3, 19));
}