Friday 21 November 2014

Processing

Exploding Images 


In the most recent Processing workshop that I have had we learnt how to make a picture burst into many particles on the click of a mouse. The main reason for this workshop was to introduce us to the use of vectors and classes that previously I did not have much experience with. The code itself basically involves setting up a number of variables, loading the image and setting the size of the canvas to the size of the image. The code has been written so that gravity, position and velocity are linked together which means that when velocity is bound to Y, it has use of all of the forces. 



The Code

PImage img;
PVector grav;
ArrayList agents;
int p = 2;
float r,g,b;

void setup(){
  background(255);
  img = loadImage("apple.jpg");
  size(img.width,img.height);
  agents = imageToAgents();
}

void draw(){
  background(255);
  
  
  for (int i = 0; i < agents.size(); i++) {
     Agent tempA = (Agent)agents.get(i);
     if (mousePressed){
       tempA.update();
     }
     tempA.draw(); 
  }
}

ArrayList imageToAgents() {
  ArrayList agents = new ArrayList();
  img.loadPixels();
  for(int x = 0; x < img.width; x += p){
    for (int y = 0; y < img.height; y += p){
      int loc = x + (y * img.width);
      color c = img.pixels[loc];
      Agent pixel = new Agent(x,y,c);
      agents.add(pixel);      
    }
   }
 return agents;
}

class Agent {
    PVector pos,vel,grav,force;
    float x,y;
    color c;

    Agent(int x, int y, color c){
     this.x = x;
     this.y = y;
     this.c = c;
     grav = new PVector (0,random(0.5,1));
     pos = new PVector (x,y);
     force = new PVector();
     vel = new PVector(random(-9,9),random(-9,9));
    }
    
    void update(){
        force.set(grav);
        vel.add(force);
        vel.mult(0.99);
        pos.add(vel);
    }
    
    void draw() {
      fill(c);
      noStroke();
      rect(pos.x,pos.y,p,p); 
    }
}

No comments:

Post a Comment