// Shirley Chen
// Section B
// junfanc@andrew.cmu.edu
// Projecct 10
var mushrooms = [];
var pigs = [];
//Load two images of the pig
function preload(){
var filenames = [];
filenames[0] = "https://i.imgur.com/DmGVjxo.png";
filenames[1] = "https://i.imgur.com/WuMtlCY.png";
for (var i = 0; i < filenames.length; i++) {
pigs.push(loadImage(filenames[i]));
}
}
function setup() {
createCanvas(480, 480);
//Create the giant mushroom moving at the background
for (var i = 0; i < 10; i++){
var rx = random(width);
mushrooms[i] = makeMushroom(rx);
}
frameRate(10);
}
function draw(){
background(202, 220, 249);
noStroke();
fill(135, 196, 165);
rect(0, 300, 480, 180);
fill(255, 214, 119);
ellipse(480, 0, 200, 200);
updateAndDisplayMushrooms();
removeMushroomsThatHaveSlippedOutOfView();
addNewMushroomsWithSomeRandomProbability();
//Display the two images alternatively to create motion
push();
//Flip the direction of the pig
scale(-1, 1);
image(pigs[frameCount % 2], -230, height / 2);
pop();
}
function updateAndDisplayMushrooms(){
// Update and display the mushrooms
for (var i = 0; i < mushrooms.length; i++){
mushrooms[i].move();
mushrooms[i].display();
}
}
function removeMushroomsThatHaveSlippedOutOfView(){
var mushroomsToKeep = [];
for (var i = 0; i < mushrooms.length; i++){
if (mushrooms[i].x + mushrooms[i].breadth > 0) {
mushroomsToKeep.push(mushrooms[i]);
}
}
mushrooms = mushroomsToKeep;
}
function addNewMushroomsWithSomeRandomProbability() {
// With a very tiny probability, add a new mushroom to the end.
var newmushroomLikelihood = 0.007;
if (random(0,1) < newmushroomLikelihood) {
mushrooms.push(makeMushroom(width));
}
}
// Update the position of building for every frame
function mushroomMove() {
this.x += this.speed;
}
// Draw the mushrooms
function mushroomDisplay() {
var mushroomHeight = this.nHeight * 20;
fill(255);
stroke(252, 190, 181);
push();
translate(this.x, height - 180);
rect(0, -mushroomHeight, this.breadth, mushroomHeight, 15);
pop();
push();
translate(this.x, height - 180);
fill(252, 161, 148);
arc((this.breadth / 2), -mushroomHeight+10, (this.breadth + 60), (mushroomHeight*0.8), PI, 0);
stroke(200);
pop();
}
function makeMushroom(locationX) {
var mushroom = {x: locationX,
breadth: 40,
speed: -1.0,
nHeight: round(random(2,8)),
move: mushroomMove,
display: mushroomDisplay}
return mushroom;
}
For this project, I created a series of giant mushrooms at the background. Learning from the base code provided from the assignment requirement, I used object command to generate rectangles and semicircle to represent a mushroom. Then, I used translate command to move them to the position I want them to be at. I also loaded two images of the pig and displayed them alternatively to create a flying motion. For this project I think it is a good practice for the previous projects relating to load images and also help me to practice my use of object command. It also helps me with previewing the scale command that flip the canvas to the opposite side.
Sketch :