xxxxxxxxxx
55
// An array for each parameter of a ball
let xs = [];
let xspeeds = [];
let ys = [];
let yspeeds = [];
function setup() {
createCanvas(400, 400);
// Populate my array of xs, xspeeds, ys and yspeeds
for(let b = 0; b < 10; b++) {
xs[b] = random(width);
xspeeds[b] = random(-5, 5);
ys[b] = random(height);
yspeeds[b] = random(-5, 5);
// Alternate way to add to an array
//xs.push(random(width));
}
}
function draw() {
background(220);
// Look through all the x-positions to...
for(let b = 0; b < xs.length; b++) {
// Update the bth ball location
xs[b]+=xspeeds[b];
ys[b]+=yspeeds[b];
// Test whether to bounce the bth ball
if(xs[b] < 0 || xs[b] > width) {
xspeeds[b] *= -1;
}
if(ys[b] < 0 || ys[b] > height) {
yspeeds[b] *= -1;
}
// Display the bth ball
ellipse(xs[b], ys[b], 50, 50);
}
}
// Dynamically add to the array of balls when user presses the mouse.
// This cannot be done with variables.
function mousePressed() {
xs.push(mouseX);
ys.push(mouseY);
xspeeds.push(random(-1,1));
yspeeds.push(random(-1, 1));
console.log(xs.length);
}