読者です 読者をやめる 読者になる 読者になる

Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

ネットワーク上を動き回る点

/**
* movers on network
*
* @author aa_debeb
* @date 2016/10/07
*/

int num = 8;
float radious = 200;
ArrayList<Node> nodes;
ArrayList<Mover> movers;
color c;

void setup(){
  size(640, 640);
  mousePressed();
}

void mousePressed(){
  nodes = new ArrayList<Node>();
  for(int i = 0; i < num; i++){
    float angle = i * TWO_PI / num - HALF_PI;
    Node node = new Node(radious * cos(angle), radious * sin(angle)); 
    for(Node other: nodes){
      if(random(1) < 0.5){
        node.addNeighbor(other);
        other.addNeighbor(node);
      }
    }
    nodes.add(node);
  }
  ArrayList<Node> tempNodes = new ArrayList<Node>();
  for(Node node: nodes){
    if(node.neighbors.size() != 0){
      tempNodes.add(node);    
    }
  }
  nodes = tempNodes;
  
  movers = new ArrayList<Mover>();
  for(int i = 0; i < 30; i++){
    movers.add(new Mover());
  }
  
  c = color(random(255), random(255), random(255));
}

void draw(){
  background(255);
  translate(width / 2, height / 2);  
  for(Node node: nodes){
    noStroke();
    fill(c);
    ellipse(node.loc.x, node.loc.y, 20, 20);
    stroke(c);
    strokeWeight(3);
    for(Node neighbor: node.neighbors){
      line(node.loc.x, node.loc.y, neighbor.loc.x, neighbor.loc.y);
    }
  }
  stroke(c);
  strokeWeight(3);
  fill(255);
  for(Mover mover: movers){
    ellipse(mover.loc.x, mover.loc.y, 10, 10);
    mover.update();
  }
}

class Node{

  PVector loc;
  ArrayList<Node> neighbors;

  Node(float x, float y){
    loc = new PVector(x, y);
    neighbors = new ArrayList<Node>();   
  }
  
  void addNeighbor(Node n){
    neighbors.add(n);
  }
  
  
}

class Mover{
  
  PVector loc;
  Node fromNode, toNode;
  
  Mover(){
    fromNode = nodes.get(int(random(nodes.size())));
    toNode = fromNode.neighbors.get(int(random(fromNode.neighbors.size())));
    loc = new PVector(fromNode.loc.x, fromNode.loc.y);
  }
  
  void update(){
    PVector vel = PVector.sub(toNode.loc, loc);
    vel.limit(3);
    loc.add(vel);
    if(PVector.dist(loc, toNode.loc) <= 0.1){
      fromNode = toNode;
      loc.x = fromNode.loc.x;
      loc.y = fromNode.loc.y;
      toNode = fromNode.neighbors.get(int(random(fromNode.neighbors.size())));
    }
  }
  
}
f:id:aa_debdeb:20160930212024j:plain