Marcius226
Marcius226

Reputation: 21

p5.js multiple bouncing balls

So I have a file with a class which describes a ball. And a main file which calls them and and them to the array. All I want to do is to bounce the ball back and forward, I can manage to do this with 1 ball, but then I add them more they are bouncing together (closest to the edge bounce all of them) all I want is to make them bounce individually. (Ball class and main code is in different files).

// ball class ***********
let speed = 5;
class Ball {
  constructor() {
    this.x = mouseX;
    this.y = mouseY;
    this.r = 30;
    this.col = color(123, 125, 255, 50);
  }
  show() {
    stroke(255);
    fill(this.col);
    ellipse(this.x, this.y, this.r * 2);
  }
  move() {
    if (this.y > height - this.r || this.y < 0 + this.r) {
      speed = speed * -1;
    }
    this.y = this.y + speed;
  }
}

//main code***********************
var balls = [];

function setup() {
  createCanvas(600, 400);
  for (var i = 0; i < balls.length; i++) {
    balls[i] = new Ball;
  }
}

function draw() {
  background(0);
  for (var i = 0; i < balls.length; i++) {
    balls[i].show();
    balls[i].move();
  }
}

function mousePressed() {
  for (var i = 0; i < 1; i++) {
    balls.push(new Ball);
  }
}

Upvotes: 2

Views: 1778

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42174

You've declared speed outside your Ball class, which means it is shared between all Ball instances.

Move it inside the Ball class, exactly like you've already done with x, y, r, and col.

Also note that you should have () parentheses after a constructor. So new Ball() instead of new Ball.

Oh and one more thing, the loop in setup() isn't doing anything, because at that point your balls array has a length of 0.

Upvotes: 1

Related Questions