Video

Generative Art Experiments – Vector movement

Unfortunately your browser is not able to show this content.

You can download vector_mover_mouse.pde (Sourcecode) and compile it with Processing.

Here is an experiment showing basic movement using Vector Math. In this sketch our objects move towards the mouse, left mouse click to add another object, right mouse to remove all objects.

Here is the code for this sketch (adapted from an example in the awesome book “The Nature of Code“):

ArrayList movers;

void setup(){
  
  movers = new ArrayList();
  Mover mover = new Mover();
  movers.add(mover);
  
  size(807,425);
  frameRate(30);
  background(0);
  
}

void draw(){
  
  background(0);
  
  for(int i = 0; i< movers.size();i++){
    
    Mover mover = (Mover)movers.get(i);
    mover.update();
    mover.checkEdges();
    mover.display();
  }
 
}

void mousePressed(){
  
   //clear if right mouse is clicked
  if (mouseButton == RIGHT) {
    movers.clear();
  }
  
  //add a new mover object
  Mover mover = new Mover();
  movers.add(mover);
   
}

//classes
class Mover {
  
  PVector location;
  PVector velocity;
  PVector acceleration;
  float topspeed;
  
  Mover(){
    
    location = new PVector(width/2,height/2);
    velocity = new PVector(0,0);
    topspeed = 10;
    
  }
  
  void update(){
    
    //calculate direction to mouse
    PVector mouse = new PVector(mouseX,mouseY);
    PVector dir = PVector.sub(mouse,location);
    
    //create acceleration from direction
    dir.normalize();
    dir.mult(0.5);
    acceleration = dir;
    
    velocity.add(acceleration);
    velocity.limit(topspeed);
    location.add(velocity);
    
  }
  
  void display(){
    stroke(0);
    fill(175);
    ellipse(location.x,location.y,16,16);
    
  }
  
  void checkEdges(){
    
    if(location.x > (width - 10) || location.x < 10){
      velocity.x = velocity.x *-1;
    }
    if(location.y > (height - 10) || location.y < 10){
      velocity.y = velocity.y *-1;
    }
    
  }
  
}