Last active
November 5, 2020 03:33
-
-
Save nickgs/d9f9ac00b837d94452a1c4136abf619d to your computer and use it in GitHub Desktop.
Introducing Classes and Objects.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Illustrates the basics of object oriented programming. | |
A class defines a blueprint to create something. The `new` operator builds an objects from that class. | |
*/ | |
function setup() { | |
createCanvas(windowWidth, windowHeight); | |
background("blue"); | |
let cloud1 = new Cloud(50, 60); | |
cloud1.draw(); | |
let cloud2 = new Cloud(450, 100); | |
cloud2.draw(); | |
let cloud3 = new Cloud(650, 160); | |
cloud3.draw(); | |
let ground = new Ground(); | |
ground.draw(); | |
let tree1 = new Tree(100, windowHeight-150); | |
tree1.draw(); | |
let tree2 = new Tree(400, windowHeight-150); | |
tree2.draw(); | |
} | |
function draw() { | |
} | |
// Lets define some clouds. | |
class Cloud { | |
constructor(x, y) { | |
console.log("Building new cloud"); | |
this.cloudSizes = [50, 40, 40]; | |
this.x = x; | |
this.y = y; | |
} | |
draw() { | |
// lets teach the computer to draw a cloud. | |
fill("white"); | |
noStroke(); | |
for(let i = 0; i < this.cloudSizes.length; i++) { | |
ellipse(this.x+(30*i), this.y, this.cloudSizes[i]); | |
} | |
} | |
} | |
class Ground { | |
constructor() { | |
} | |
draw() { | |
fill("green"); | |
rect(0, windowHeight-50, windowWidth, 50); | |
} | |
} | |
class Tree { | |
constructor(x, y) { | |
this.x = x; | |
this.y = y; | |
} | |
draw() { | |
// Lets draw the trunk | |
fill("brown"); | |
rect(this.x, this.y, 30, 100); | |
// Lets draw the leaves. | |
fill("green"); | |
ellipse(this.x - 10, this.y, 100); | |
ellipse(this.x + 50, this.y, 50); | |
ellipse(this.x + 30, this.y - 50, 80); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment