How to make a Snowflake in Processing


Code of particle.pde:

class Particle {

  PVector pos;
  float r;

  Particle(float radius, float angle) {
    pos = PVector.fromAngle(angle);
    pos.mult(radius);
    r = 3;
  }

  void update() {
    pos.x -= 1;
    pos.y += random(-3, 3);

    float angle = pos.heading();
    angle = constrain(angle, 0, PI/6);
    float magnitude = pos.mag();
    pos = PVector.fromAngle(angle);
    pos.setMag(magnitude);
  }

  void show() {
    fill(255);
    stroke(255);
    ellipse(pos.x, pos.y, r * 2, r *2);
  }

  boolean intersects(ArrayList<Particle> snowflake) {
    boolean result = false;
    for (Particle s : snowflake) {
      float d = dist(s.pos.x, s.pos.y, pos.x, pos.y);
      if (d < r*2) {
        result = true;
        break;
      }
    }
    return result;
  }

  boolean finished() {
    return (pos.x < 1);
  }
}

Code of snowflake.pde:

Particle current;
ArrayList<Particle> snowflake;

void setup() {
  // size(600, 600);
  fullScreen();
  current = new Particle(width/2, 0);
  snowflake = new ArrayList<Particle>();
}

void draw() {
  translate(width/2, height/2);
  rotate(PI/6);
  background(0);

  int count = 0;
  while (!current.finished() && !current.intersects(snowflake)) {
    current.update();
    count++;
  }

  // If a particle doesn't move at all we're done
  // This is an exit condition not implemented in the video
  if (count == 0) {
    noLoop();
    println("snowflake completed");
  }

  snowflake.add(current);
  current = new Particle(width/2, 0);

  for (int i = 0; i < 6; i++) {
    rotate(PI/3);
    current.show();
    for (Particle p : snowflake) {
      p.show();
    }

    pushMatrix();
    scale(1, -1);
    current.show();
    for (Particle p : snowflake) {
      p.show();
    }
    popMatrix();
  }
}

Comentarios

Entradas populares de este blog

How to do an Email Bomber with Python

How to make a Christmas animation in HTML

Chat with Firebase