xxxxxxxxxx
var squares = []; //An array of squares
function setup() { //Same as "void setup"
createCanvas(windowWidth, windowHeight); //Create a "size" of the whole window
background(0); //Black background
}
function draw() { //Same as "void draw;"
if (keyIsPressed) { //Press any key to clear screen
background(0); //Black background
}
if (mouseIsPressed) { //If the mouse is pressed
//Make a new square with a random color
var s = new square(mouseX, mouseY, color(random(255), random(255), random(255)), 10, 10);
squares.push(s); //Add the square to our array
}
for (var i = squares.length - 1; i > 0; i--) { //Loop through each square
var s = squares[i]; //Get the square
s.render(); //Draw it
s.update(); //Move it
if (s.getWidth() <= 0) { //Check if it is now invisible
var newarray = subset(squares, 0, i); //Get the left half of the remaining squares
//NOTE: REMOVING ELEMENTS IN JAVASCRIPT IS HARDER THAN Processing 3.0/Java!
var startLeft = squares.length - (squares.length - 1 - i); //The index to start at for removing square
var amountLeft = squares.length - i - 1; //The number of squares from index to end of array
var array2 = subset(squares, startLeft, amountLeft); //Get the right half of the remaining squares
//Add the two (left and right) halves together (removing the dead square)
var arrayfinal = concat(newarray, array2);
squares = arrayfinal; //Update our list of squares
}
}
}
function square(x, y, c, w, h) { //A "square" class, we could have named it anything we like
this.x = x; //The X position of this square
this.y = y; //The Y position of this square
this.color = c; //The color of this square
this.w = w; //The width of this square
this.h = h; //The height of this square
this.update = function(ival) { //A function to update the square
this.x += random(10) - random(10); //"jitter" X position randomly
this.y += random(10) - random(10); //"jitter" Y position randomly
if (this.x < 0) this.x = windowWidth; //If we are left of the left edge, move to right
if (this.y < 0) this.y = windowHeight; //If we are below the bottom edge, move to top
if (this.x > windowWidth) this.x = 0; //If we are right of the right edge, move to left
if (this.y > windowHeight) this.y = 0; //If we are above the top edge, move to bottom
this.w -= 0.1; //Shrink
}
this.render = function() { //A function to draw the square on screen
noStroke(); //No outline
fill(c); //Fill color
rect(this.x, this.y, this.w, this.h); //Draw the square
}
this.getX = function() {
return this.x; //A function to get our square X position
}
this.getY = function() {
return this.y; //A function to get our square Y position
}
this.getWidth = function() {
return this.w; //A function to get our square width
}
this.getHeight = function() {
return this.h; //A function to get our square height, unused right now!
}
}