xxxxxxxxxx
56
let rectangles = [];//creates an empty list to store rectangle objects
let num_rectangles = 50; //number of rectangles
function setup() {
createCanvas(600, 600);
for (let i = 0; i < num_rectangles; i++) {//creates as many rectangle objects as specified in the num variable by using a for loop
let rect_object = {
//-100 ensures some rectangles are not created beyond the borders of the screen
x: random(width-100),
y: random(height-100),
//randomly selects width and height for the rectangle between 30 and 100
w: random(30, 100),
h: random(30, 100),
color: [random(255), random(255), random(255), random(100,200)],
// randomly selects RGB values from 0-255 to make unique colors for each rectangle, a 4th input alpha is given to make the rectangles translucent, this is also randomly chosen within a range to ensure all rectangles remain visible
speed_x: random(1, 3),
speed_y: random(1, 3),
//randomly selects the speed of each object within a certain range
dir_x: random([-1, 1]),
dir_y: random([-1, 1])
//randomly chooses whether each object will go up/down & left/right
};
rectangles.push(rect_object);//all rectangle objects created using the for loop are added to the rectangles list
}
}
function draw() {
background(255); // white background
for (let rect_object of rectangles) {//loops through each rectangle object in the list and assigns it color based on the random color chosen before
fill(rect_object.color);
noStroke(); //removes stroke from each rectangle
rect(rect_object.x, rect_object.y, rect_object.w, rect_object.h, 15);
//creates each rectangle according to the x,y position and width and height decided before. another last factor is added for corner radius to round out each rectangle
if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {
//if statement checks whether mouse is inside the canvas by analyzing x and y positions
//if inside the canvas, the x and y values of each rectangle is changed based on its speed and direction value which was assigned in the setup function
rect_object.x += rect_object.speed_x * rect_object.dir_x;
rect_object.y += rect_object.speed_y * rect_object.dir_y;
//this checks whether the object is hitting the horizontal border by analyzing if the left or right side of the rectangle have exited the canvas, it then reverses the rectangle's direction to ensure it stay on screen
if (rect_object.x <= 0 || rect_object.x + rect_object.w >= width) {
rect_object.dir_x *= -1; // Reverse horizontal direction
}
//this checks whether the object is hitting the vertical border by analyzing if the top or bottom side of the rectangle have exited the canvas, it then reverses the rectangle's direction to ensure it stay on screen
if (rect_object.y <= 0 || rect_object.y + rect_object.h >= height) {
rect_object.dir_y *= -1; // Reverse vertical direction
}
}
}
}