Neathed Studios
Neathed Studios

Reputation: 11

When I run this code on p5 editor, I get an error on line 0

  class Bubble {

    constructor() { 
      var allInstances = [];
      createCanvas(600,600);
      var radius = random(10,100);
      this.x = random(0, 600);
      this.y = random(0, 600);
      this.width = radius;
      this.height = radius;
      var x = random(0,300);
      var y = random(0,300);
      var z = random(0,300);
      this.velocityX = random(-5, +5);
      this.velocityY= random(-5, +5);

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

// the below block of code is the one I am having trouble with. the bubbles do not bounce off of the vertical edges of the screen.

      if(this.x > 600  || this.x < 0) { 
        this.velocityX = this.velocityX * -1; 

// the above block of code is the one I am having trouble with

      }

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

    }
  }

Edit:

The program runs and multiple bubbles appear in the way the program is shown above, but I cannot get them to bounce off of the sides of the canvas. Can you help me?

Upvotes: 1

Views: 60

Answers (1)

Rabbid76
Rabbid76

Reputation: 210889

Answer to:

[...] but I cannot get them to bounce off of the sides of the canvas. [...]

You have to evaluate if the bubbles hit side of the canvas and to change the direction of the bubbles in Bubble.move:

class Bubble {
    // [...]

    constructor() { 
        // [...]

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

            if (this.x > 600-this.radius || this.x < this.radius) { 
                this.velocityX *= -1; 
            }
            if (this.y > 600-this.radius || this.y < this.radius) { 
                this.velocityY *= -1; 
            }
        }
    }
}

Upvotes: 1

Related Questions