Recitation 10: Object Oriented Programming Workshop by Yu Yan (Sonny)

For this recitation, we first went through the content about “map()” function concerning what it is used for and how to use it. After this, we went separately to attend different workshops. I participated in the Object Oriented Programming workshop hosted by Tristan. 

During the workshop, we learned about two parts of an “object”, “class” and “instance”, and how to use them. By using “class”, we can make our code more concise and clear to read. We can also use “ArrayList” to create multiple objects. 

Exercise:

For exercise, I created a “class” called “Image” that generated two ellipses and one rectangle. I put them into random colors and set 20 of them off from the center of the canvas. For interaction, I used a “mouseMoved” function so that it can display the images based on the location of my mouse.

Here is the animation of my work.

Here is my code:

ArrayList<Image> images;

void setup(){
  size(1000,600);
  colorMode(HSB,360,100,100);
  images = new ArrayList<Image>();
  
  for(int i=0; i<20; i++){
    images.add(new Image(width/2, height/2,random(-5,5),random(-5,5),color(random(360),100,100)));    
  }
}

void draw(){
  background(270,100,100);
  
  for(int i=0; i<images.size(); i++){
    Image temp = images.get(i);
    temp.display();
    temp.move();
  }  
}

void mouseMoved(){
  images.add(new Image(mouseX,mouseY,random(-5,5),random(-5,5),color(random(360),100,100)));    
}

class Image{
  float x,y,spdX,spdY;
  color c;
  
  Image(float newX, float newY, float newSpdX, float newSpdY, color newC){
    spdX = newSpdX;
    spdY = newSpdY;
    c = newC;
    
    x = newX;
    y = newY;
  }
  
  void move(){
    x += spdX;
    y += spdY;
    if (x > width || x < 0){
      spdX *= -1;
    }
    if (y > height || y < 0){
      spdY *= -1;
    }
  }
  
  void display(){
    fill(c);
    ellipse(x,y,30,30);
    ellipse(x+40,y,30,30);
    rect(x,y,40,40);
  }
}

Leave a Reply