xxxxxxxxxx
// Having fun with arrays: combining motion + arrays 2
// Practicing using arrays
let n = 100;
let x = new Array(n);
let y = new Array(n);
let speedx = new Array(n);
let speedy = new Array(n);
function setup() {
createCanvas(400, 400);
for (let i = 0; i < y.length; i++) {
x[i] = random(width);
y[i] = random(height);
speedx[i] = random(-2, 2);
speedy[i] = random(-2, 2);
}
}
function draw() {
background(255,120,0);
fill(255, 100);
noStroke();
for (let i = 0; i < y.length; i++) {
// draw
ellipse(x[i], y[i], 20, 20);
// update the ellipse's position for the next 'frame' (so it will move).
x[i] = x[i] + speedx[i]; // Another way to write this is x[i] += speedx[i].
if (x[i] < 0 || x[i] > width) { // If x[i] is less than 0 or greater than the width...
speedx[i] = -speedx[i]; // ...then change the direction it's moving in.
}
y[i] += speedy[i]; // This is the same as saying y[i] = y[i] + speedy[i]. It's just quicker.
if (y[i] < 0 || y[i] > height) speedy[i] = -speedy[i]; // This is the same as the '*' below, but quicker.
}
}
// * Two ways to write the following.
// Method 1:
// if (y[i] < 0 || y[i] > height) {
// speedy[i] = -speedy[i];
// }
// Method 2:
// if (y[i] < 0 || y[i] > height) speedy[i] = -speedy[i];
// Experiment:
// Try commenting out lines 28-33. What happens? Why?
// Try commenting out lines 28-30. What happens? Why?
// Try to make the ellipses all move twice as fast as they do now.
// Try to make all the elipses begin by all moving to the right and/or down.
// Try to make all the elipses begin by all moving to the left and/or up.