sketch
Trees and birds and trees and birds
var trees = [];
var birds = [];
var dx = -1;
function setup() {
createCanvas(400, 200);
for (var i = 0; i < 10; i++){ //populate trees
var rx = random(width);
trees[i] = makeTree(rx);
}for (var i = 0; i < 3; i++){ //populate birds
var bx = random(width);
birds[i] = makeTree(bx);
}
frameRate(10);
}
function draw() {
background('lightblue');
//dirt
noStroke();
fill('darkgreen');
rect(-10, 100, width+20, height);
updateAndDisplayTrees();
removeTree();
newTree();
updateAndDisplayBird();
removeBird();
newBird();
drawRoad();
}
function drawRoad() {
fill('grey');
rect(-10, 130, width+20, 30);
stroke('black');
var dividerLines = [];
for (var i = 0; i < 30; i++) { //make vals
var a = i*width/30;
dividerLines.push(a);
} for (var i = 0; i < 30; i++) { //draw lines
line(dividerLines[i], 145, dividerLines[i]+width/60, 145);
} for (var i = 0; i < 30; i++) { //move lines
dividerLines[i] += dx;
if (dividerLines[i] <= -width/60) {
dividerLines[i] = width;
}
}
}
function updateAndDisplayTrees(){
for (var i = 0; i < trees.length; i++){
trees[i].move();
trees[i].display();
}
}
function updateAndDisplayBird(){
for (var i = 0; i < birds.length; i++){
birds[i].move();
birds[i].display();
}
}
function removeTree(){
var treesToKeep = [];
for (var i = 0; i < trees.length; i++){
if (trees[i].x > -50) {
treesToKeep.push(trees[i]);
}
}
trees = treesToKeep;
}
function removeBird(){
var birdsToKeep = [];
for (var i = 0; i < birds.length; i++){
if (birds[i].x > -50) {
birdsToKeep.push(birds[i]);
}
}
birds = birdsToKeep;
}
function newTree() {
var newTreeLikelihood = 0.02;
if (random(0,1) < newTreeLikelihood) {
trees.push(makeTree(width+50));
}
}
function newBird() {
var newBirdLikelihood = 0.05;
if (random(0,1) < newBirdLikelihood) {
birds.push(makeBird(width));
}
}
// method to update position of Tree every frame
function treeMove() {
this.x += this.speed * this.scal/3;
}
function birdMove() {
this.x += this.speed;
}
function treeDisplay() {
push();
translate(this.x, 100);
scale(this.scal)
stroke('brown');
strokeWeight(5);
line(0, 0, 0, 20);
stroke('green');
fill('green');
for (var i = 0; i < 5; i++) {
triangle(-20+2*i, -7*i, -2, -7*i, -2, -20-7*i);
} for (var i = 0; i < 5; i++) {
triangle(20-2*i, -7*i, 2, -7*i, 2, -20-7*i);
}
pop();
}
function birdDisplay() {
push();
translate(this.x, this.y);
stroke('black');
noFill();
strokeWeight(2);
arc(0, 0, 20, 20, PI+PI/3, 2*PI-PI/3);
arc(10, 0, 20, 20, PI+PI/3, 2*PI-PI/3);
pop();
}
function makeTree(birthLocationX) {
var tree = {x: birthLocationX,
scal: random(0.5, 2),
speed: dx,
move: treeMove,
display: treeDisplay}
return tree;
}
function makeBird(birthLocationX) {
var bird = {x: birthLocationX,
y: random(0, 70),
speed: random(-5,-2),
move: birdMove,
display: birdDisplay}
return bird;
}