lundi 4 mai 2020

Is there a way to endlessly add one bubble at a time to a canvas using a pre-made `Bubble` class?

Here is the link to my project: https://editor.p5js.org/darkknightishaan/sketches/mXgN5Z_72

Right now, I am using the setup() function to create a canvas and create the bubbles. I tried moving the Bubble variable declaration to its own function before and after the setup() function and also in the draw() function and outside of both functions. I also tried moving the canvas creation to a different part, but none of these solutions work. How can I tweak this code to make it create a new bubble in the canvas every 0.5s instead of resetting the canvas and bubbles every 2.9s?

class Bubble {

  constructor() {
    let allInstances = [];

    let radius = random(20, 200);
    let red = random(210, 255);
    let randRed = parseInt(red);
    let alpha = random(0.25, 0.6);
    let randAlpha = alpha.toFixed(2);
    let color = `rgba(${randRed},255,255,${randAlpha})`;
    this.x = random(100, 700);
    this.y = random(100, 500);
    this.width = radius;
    this.height = radius;
    this.color = color;
    this.velocityX = random(-5, +5);
    this.velocityY = random(-5, +5);

    this.display = function() {
      stroke(255);
      fill(this.color);
      ellipse(this.x, this.y, this.width, this.height);
    }

    this.move = function() {
      this.x = this.x + this.velocityX;
      this.y = this.y + this.velocityY;
    }

  }
}
/*
var bubbles = [];

function setup() {
  createCanvas(800, 600);
  bubble1 = new Bubble();
  bubble2 = new Bubble();
  bubble3 = new Bubble();
  bubble4 = new Bubble();
  bubble5 = new Bubble();
  bubble6 = new Bubble();
}


function draw() {
  background(56, 226, 232);
  bubble1.move();
  bubble2.move();
  bubble3.move();
  bubble4.move();
  bubble5.move();
  bubble6.move();

  bubble1.display();
  bubble2.display();
  bubble3.display();
  bubble4.display();
  bubble5.display();
  bubble6.display();
}

setInterval(function() {
  setup();
  draw();
}, 2900);
*/
html,
body {
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.min.js"></script>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta charset="utf-8" />
  <script src="Bubble.js"></script>
</head>

<body>
  <script src="sketch.js"></script>
</body>

</html>

Here is my code, the commented code is my current JavaScript code which has the aforementioned setup() and draw functions and the Bubble class.




Aucun commentaire:

Enregistrer un commentaire