Recitation 10: Object Oriented Programming by Lifan Yu

Recitation 10: Object Oriented Programming by Lifan Yu (ly1164)

My object called “Plastic” contain all images of plastic bottles and their movements. This way, we can not only control the common ways of their movements (or their common parameters)  but also control their movements and parameters individually.

Source of the used image: Lifan Yu

Code:

ArrayList<Plastic> plasticList;
 PImage img2;
 
 void setup(){
   size(800,800);
 plasticList = new ArrayList<Plastic>();
  img2=loadImage("plastic.png");
 }
 
 void draw(){
   background(255);
   imageMode(CENTER);
    for(int k=0; k<plasticList.size(); k++){
    Plastic temp=plasticList.get(k);
    temp.display();
    temp.move();
   
  }
 }
 
 
   void keyPressed(){
  float x=map(mouseX,0,width,width/4,3*width/4);
  float y=map(mouseY,0,height,height/4,3*height/4);
  plasticList.add(new Plastic(x,y));
  
    
}

Create another tag called “Plastic”:

class Plastic {

  float x,y;
  float size;
  float speedX;
  float speedY;
  Plastic(float startingX, float startingY){
    x=startingX; 
    y=startingY;
    size=random(50,150);

    speedX=random(-10,10);
    speedY=random(1,15);
  }

    void display(){
      image(img2,x,y,size,size);
  }
  

  void move(){
    x+=speedX;
    y+=speedY;
    if(x<=0||x>=width){
      speedX=-speedX;
    }
    
    if(y<=0||y>=height){
      speedY=-speedY;
    }
    
  }
  
}

Leave a Reply