如何在一帧中创建多个对象? (创意编码)
How to create multiple objects in one single frame? (Creative Coding)
我一直在开始创意编码,但现在遇到了一个小问题:我写了一个 class 来构建一个 "Raindrop" 并使用一个数组和一个 for 循环,我设法制作了一个下雨般的动画。但目前,每帧只生成 1 个雨滴。但我打算每帧生成 5 个雨滴。我想每帧调用 class 5 次。
这是我的代码:
class drop {
constructor(x,y1,y2,vel) { //constructor function
this.vel = vel;
this.x1 = this.x2 = x;
this.y1 = y1;
this.y2 = y2;
}
move () {
this.y1 = this.y1 + this.vel;
this.y2 = this.y2 + this.vel; //describing the movement of the raindrop.
}
show () {
line(this.x1,this.y1,this.x2,this.y2); //show the actual raindrop
}
}
这就是我的 class 到目前为止。由于 p5.js 框架,我得到了一个所谓的绘制函数,它一遍又一遍地循环代码(每秒 60 次)。看起来像这样:
function draw () {
let randomWidth = random(0,width);
let randomLength = random(0,40);
let randomVelocity = random(10,15);
let d = new drop (randomWidth,0,randomLength,randomVelocity); //pushes the drops to the array
rain.push(d);
for (let i = 0; i < rain.length; i++) { //for-loop to display the raindrops
rain[i].move();
rain[i].show();
if (rain.length > 250) { //cap the maximum amount of array indexes
rain.splice(i,1);
}
}
这段代码到目前为止运行完美,每帧有一个 drop-call,但我希望雨下得更大,所以 drop spawn 的频率必须增加。我还不太熟悉 for 循环,但我相信这可以很容易地用一个来解决。
这是添加单个雨滴的逻辑:
let randomWidth = random(0,width);
let randomLength = random(0,40);
let randomVelocity = random(10,15);
let d = new drop (randomWidth,0,randomLength,randomVelocity); //pushes the drops to the array
rain.push(d);
如果你想创建多个雨滴,你不能把这个逻辑放在一个循环中吗?或者更好的是,将其移至 addRaindrop()
函数并在循环内调用该函数。
我一直在开始创意编码,但现在遇到了一个小问题:我写了一个 class 来构建一个 "Raindrop" 并使用一个数组和一个 for 循环,我设法制作了一个下雨般的动画。但目前,每帧只生成 1 个雨滴。但我打算每帧生成 5 个雨滴。我想每帧调用 class 5 次。
这是我的代码:
class drop {
constructor(x,y1,y2,vel) { //constructor function
this.vel = vel;
this.x1 = this.x2 = x;
this.y1 = y1;
this.y2 = y2;
}
move () {
this.y1 = this.y1 + this.vel;
this.y2 = this.y2 + this.vel; //describing the movement of the raindrop.
}
show () {
line(this.x1,this.y1,this.x2,this.y2); //show the actual raindrop
}
}
这就是我的 class 到目前为止。由于 p5.js 框架,我得到了一个所谓的绘制函数,它一遍又一遍地循环代码(每秒 60 次)。看起来像这样:
function draw () {
let randomWidth = random(0,width);
let randomLength = random(0,40);
let randomVelocity = random(10,15);
let d = new drop (randomWidth,0,randomLength,randomVelocity); //pushes the drops to the array
rain.push(d);
for (let i = 0; i < rain.length; i++) { //for-loop to display the raindrops
rain[i].move();
rain[i].show();
if (rain.length > 250) { //cap the maximum amount of array indexes
rain.splice(i,1);
}
}
这段代码到目前为止运行完美,每帧有一个 drop-call,但我希望雨下得更大,所以 drop spawn 的频率必须增加。我还不太熟悉 for 循环,但我相信这可以很容易地用一个来解决。
这是添加单个雨滴的逻辑:
let randomWidth = random(0,width);
let randomLength = random(0,40);
let randomVelocity = random(10,15);
let d = new drop (randomWidth,0,randomLength,randomVelocity); //pushes the drops to the array
rain.push(d);
如果你想创建多个雨滴,你不能把这个逻辑放在一个循环中吗?或者更好的是,将其移至 addRaindrop()
函数并在循环内调用该函数。