xxxxxxxxxx
83
//setting variables
let blocks = [];
let cols = 8;
let rows = 8;
let blockSize = 50;
function setup() {
createCanvas(420, 420);
let x = 10;
let y = 10;
//nested for loops that will generate an 8x8 grid of blocks
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
let block = new Block(x, y, r, c);
blocks.push(block); //adding the blocks to the array
x += blockSize; //moving each block to the right
}
x = 10; //resetting x for each new row
y += blockSize; //moving y down
}
}
function draw() {
background(220);
for (let i = 0; i < blocks.length; i++) {
blocks[i].show(); //displaying each item in the array
}
}
//creatign a block class
class Block {
constructor(x, y, row, col) {
//setting variables
this.x = x;
this.y = y;
this.l = blockSize;
this.row = row;
this.col = col;
this.fixedRotation = 0;
this.colorValue = 0;
//rotating the rows at the bottom half
if (this.row >= rows - 4) {
//making the level of rotation more intense as the grid goes on using map() function
let intensity = map(this.row, rows - 4, rows - 1, 5, 25); //increasign rotation for lower rows
//converting to radians for the rotate() function
this.fixedRotation = radians(random(-intensity, intensity));
} else {
this.fixedRotation = 0; //no rotation for the top rows
}
//creating a gradient from light to dark
this.colorValue = map(this.row, 0, rows - 1, 255, 50);
}
show() {
let centerX = this.x + this.l / 2;
let centerY = this.y + this.l / 2;
let theAngle = atan2(mouseY - centerY, mouseX - centerX); //triangle rotation
push();
translate(centerX, centerY);
rotate(this.fixedRotation);
//applying gradient color to squares
fill(this.colorValue);
rectMode(CENTER);
rect(0, 0, this.l, this.l); //drawing the square centered
rotate(theAngle); //rotating the triangles toward mouse
//initially drawing the triangle
fill(0);
triangle(20, 0, -20, -14, -20, 14);
pop();
}
}