How to add/push a new object to array upon mouse click in p5.js

I have this code to add a new ball to the array but strangely it doesn’t work.

let balls = [];
let num_balls = 1;
let w = 800;
let h = 600;

function setup() {
    createCanvas(w, h);
    for (let i = 0; i < num_balls; i++) {
        balls[i] = new ball(100 * i, 100);
    }
}

function draw() {
    background(0);

    for (let i = 0; i < num_balls; i++) {
        balls[i].display();
    }
}

function mousePressed() {
    let myball = new ball(mouseX, mouseY)
    balls.push(myball);
}

class ball {
    constructor(tempX, tempY) {
        this.x = tempX;
        this.y = tempY;

    }

    display() {
        ellipse(this.x, this.y, 100, 100);
    }

}

Anything amiss here? Got really puzzled. Thanks in advance.

1 Like

Beautifier.io

function draw() {
  background(0);
  for (const b of balls)  b.display();
}

Thanks for both the loop and linter! It works really well.

Do you know why using balls.length in the loop doesn’t work?

for ( let i = 0; i<balls.length; i++) b.display();

You were NOT using balls.length but num_balls instead! :face_with_monocle:

for (let i = 0; i < num_balls; i++) {

Later on I changed to balls.length and still doesn’t work…

for (let i = 0; i < balls.length; ++i) b.display(); is wrong! :scream:

Correct is for (let i = 0; i < balls.length; ++i) balls[i].display(); :nerd_face:

Other options: :sunglasses:

  • for (const b of balls) b.display();
  • balls.forEach(b => b.display());
1 Like