javascript - 如何在一个框架中创建多个对象? (创意编码)

标签 javascript loops object for-loop p5.js

我一直在开始创意编码,现在遇到了一个小问题:我编写了一个类,它构建了一个“雨滴”,并使用一个数组和一个 for 循环,我成功地制作了一个类似下雨的动画。但目前,每帧仅生成 1 个雨滴。但我打算每帧生成 5 个雨滴。我想每帧调用该类 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 生成的频率必须增加。我对 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() 函数并在循环内调用该函数。

关于javascript - 如何在一个框架中创建多个对象? (创意编码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47948990/

相关文章:

Python,Django,如何使用getattr(或其他方法)调用具有多个属性的对象?

javascript - 使用自定义 HTML 而不是 URL 打开新选项卡

javascript - 从 Jstree 禁用某些复选框

c# - 循环出 string[] 值的最简单方法是什么?

object - Series对象没有属性clip_upper

php - 嵌入位于 webroot 之外的 flv 和 swf

javascript - 在 jQuery 事件中调用函数不起作用

javascript - 有没有办法只与特定邮件收件人共享链接?

java - 循环访问一组对象

loops - 简单的 Haskell 循环