Week 3: Object Oriented Programming

This week we were asked to create using Classes in Javascript. Classes are pretty cool because they store both data and functions and can be used to create ‘instances’. An apt analogy would be comparing a class to a cookie cutter and instances to cookies that can be cut using a cookie cutter. One cookie cutter can cut out an unlimited number of cookies and this makes classes very powerful. For this week’s assignment I made a very simple graphic called ‘Cats and Dogs’ (yes, the rain proverb!) and it shows a town at night where it’s raining cats and dogs, quite literally!

The process and the code:

For this assignment I relied solely on the Reference page of p5js and random tutorials on YouTube. I spent a lot of time trying to grasp how to write classes in Javascript. In the end what I made looks very simple, but I know that a lot more can be done using classes. Most of my time in this project was spent trying to understand classes.

I created 1 class that does it all, and I called it Drop. Besides the constructor() method, the class had two other methods, update() and show():

class Drop {
  constructor() {
    this.x = random(0, width);
    this.y = random(0, -height);
  }

  update() {
    this.y = this.y + 4;
    if (this.y > height) {
      this.y = random(0, -height);
    }
  }
  show() {
    noStroke();
    fill(0);
    // ellipse(this.x, this.y, 2, 10);
    image(doge, this.x, this.y, 40, 40);
    image(catto, this.x - 30, this.y + 60, 70, 70);
  }
}

The images of the dog and the cat was uploaded on to the project directly.

What I realized about Classes:

On their own, it’s hard to figure out stuff to do with Classes. I personally feel the true benefits of classes can be reaped when used in bigger projects where a class can be act as a cog in a machine.

 

Leave a Reply