I'm currently working on a project where I want to create a program that removes particles from an array when they reach the right end of the canvas.
let P = [];
let n = 10;
function setup()
{
createCanvas(500,500);
for(let i = 0; i < n; i++)
P.push(new particle());
}
function draw()
{
background(0);
for(let i = 0; i < n; i++)
{
if(P[i].out == true)
{
P.splice(i, 1);
n--;
}
P[i].update();
P[i].plot();
console.log(P.length)
}
}
class particle
{
constructor()
{
this.brightness = 0;
this.vel = random(1);
this.dia = 3;
this.x = 0;
this.y = random(height);
this.out = false;
}
update()
{
this.x += this.vel;
if(this.x >= width)
this.out = true;
}
plot()
{
noStroke();
fill(255);
circle(this.x, this.y, this.dia);
}
}
Most of the time, everything seems to be running smoothly with my program. However, as the array size decreases after particles are removed, I encounter an error message:
Uncaught TypeError: Cannot read property 'update' of undefined
This issue is perplexing because there shouldn't be any trouble reading the 'update' function since it's been used without issues previously in the loop.