I’m new to JS and p5. I was trying to make a slider which controls the number of objects through array and for loop. But I’m facing two problems.
Problem 1.
If the slider value is above 49, it gives this error
“Cannot read property of undefined. Check the line number in error and make sure the variable which is being operated is not undefined.”
I think the array is not taking values above 49 index.
For this slider, createSlider(0,85), slider is supposed to be on 85, but it stays in 49. Here’s the code,
let bubbles = [];
let slider,s;
function setup() {
createCanvas(700, 600);
colorMode(HSB,360,100,100,1);
//creating slider
s = createSlider(0,85);
//adding bubbles with slider value through for loop
for (let i=0; i < s.value(); i++){
let a = random (width);
let b = random (height);
bubbles[i] = new ball (a,b);
}
//till this 49 index the code runs but not above it
print (bubbles[49])
}
function draw() {
background(0);
//showing, moving and bouncing bubbles
for (let i=0; i < s.value(); i++){
bubbles[i].show();
bubbles[i].move();
bubbles[i].bon();
}
}
//bubble class
class ball {
constructor(x, y) {
this.x = x;
this.y = y;
this.xd = +3;
this.yd = -5;
}
show() {
noFill();
stroke(80,50,100,.5);
strokeWeight(4);
ellipse(this.x, this.y, 40, 40);
}
move() {
this.x = this.x + random(-5, 5);
this.y = this.y + random(-6, 6);
}
bon() {
if (this.x > width || this.x < 0) {
this.x = this.x * -1;
}
if (this.y > height || this.y < 0) {
this.yd = this.y * -1;
}
}
}
Problem 2.
If I set an initial value for slider createSlider(0,85,25), the slider doesn’t go above the initial value and shows same error.
let bubbles = [];
let slider,s;
function setup() {
createCanvas(700, 600);
colorMode(HSB,360,100,100,1);
//creating slider
s = createSlider(0,85,25);
//adding bubbles with slider value through for loop
for (let i=0; i < s.value(); i++){
let a = random (width);
let b = random (height);
bubbles[i] = new ball (a,b);
}
}
function draw() {
background(0);
//showing, moving and bouncing bubbles
for (let i=0; i < s.value(); i++){
bubbles[i].show();
bubbles[i].move();
bubbles[i].bon();
}
}
//bubble class
class ball {
constructor(x, y) {
this.x = x;
this.y = y;
this.xd = +3;
this.yd = -5;
}
show() {
noFill();
stroke(80,50,100,.5);
strokeWeight(4);
ellipse(this.x, this.y, 40, 40);
}
move() {
this.x = this.x + random(-5, 5);
this.y = this.y + random(-6, 6);
}
bon() {
if (this.x > width || this.x < 0) {
this.x = this.x * -1;
}
if (this.y > height || this.y < 0) {
this.yd = this.y * -1;
}
}
}
Can anyone please share how to sort it out? Any help is really appreciated.