For this project I chose to generate a landscape of grass that is supposed to look like it is blowing in the wind. I was inspired when I was laying in the park and looking at the nature around me.
var grass = [];
function setup() {
createCanvas(640, 240);
// create an initial collection of grass
for (var i = 0; i < 100; i++){
var rx = random(width);
grass[i] = makeGrass(rx);
}
frameRate(10);
}
function draw() {
background("#badddc");
updateAndDisplayGrass();
removeGrassThatHaveSlippedOutOfView();
addNewGrassWithSomeRandomProbability();
}
function updateAndDisplayGrass(){
// Update the building's positions, and display them.
for (var i = 0; i < grass.length; i++){
grass[i].move();
grass[i].display();
}
}
function removeGrassThatHaveSlippedOutOfView(){
var GrassToKeep = [];
for (var i = 0; i < grass.length; i++){
if (grass[i].x + grass[i].breadth > 0) {
GrassToKeep.push(grass[i]);
}
}
grass = GrassToKeep; // remember the surviving grass
}
function addNewGrassWithSomeRandomProbability() {
// With a very tiny probability, add a new grass to the end.
var newGrassLikelihood = 0.17;
if (random(0,1) < newGrassLikelihood) {
grass.push(makeGrass(width));
}
}
// method to update position of the grass every frame
function grassMove() {
this.x += this.speed;
}
//draw some grass
function grassDisplay() {
var GrassHeight = 20;
var bHeight = this.nGrass * GrassHeight;
fill(255);
stroke(0);
push();
translate(this.x, height - 40);
fill('green');
noStroke();
triangle(0, -bHeight + random(20), this.breadth, bHeight, this.breadth/2, bHeight/2);
fill("#48703d");
triangle(0, -bHeight, this.breadth+random(10,20), bHeight, this.breadth/2, bHeight/2);
pop();
}
function makeGrass(birthLocationX) {
var Grass = {x: birthLocationX,
breadth: 50,
speed: -1.0,
nGrass: round(random(2,8)),
move: grassMove,
display: grassDisplay}
return Grass;
}