Tuesday 25 November 2014

Exploding image (Processing)

In this week's workshop we compiled all of the code we learnt from the "Agents" and "Vectors" workshop and was tasked to create an image which exploded on mouse click and then the pixels would disperse by forces such as velocity and gravity. The code basically involves firstly declaring variables and loading the image with   img = loadImage("apple.jpg"); and setting the size of the canvas as same size as the image. You can see that's its coded so that gravity, position and velocity are linked together which means when velocity is bound to y it has all of the forces.




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