1

I've been starting creative coding and now got a little problem: I wrote a class that builds a single "Raindrop" and with an array and a for loop, I managed to make a rainy-like animation. But for now, only 1 raindrop is spawned per frame. But I intend to spawn perhaps 5 raindrops per frame. I want to call the class 5 times per frame.

Here's my code:

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

  }
 }

So thats my class so far. And due to the p5.js Framework, ive got a so-called draw function, which loops code over and over again (60 times per second). Thats looking like this:

  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);
    }
  }

This code runs perfectly so far, with one drop-call per frame, but I want the rain to be heavier, so the frequency of drop spawn must increase. I'm not that familiar with for loops yet but I am sure this can be easily solved with one.

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

0

Here's your logic for adding a single raindrop:

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);

Can't you just put that logic inside a loop if you want to create multiple raindrops? Or better yet, move this to an addRaindrop() function and call that function inside a loop.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107