Code Club #2

17.12.2020 Code Club #2 with Elise && Pierre, reproducing a simple digital morphogenesis pattern called Diffusion Limited Aggregation (DLA)

// ##### Particle Prototype

class Particle {
  constructor() {
    this.posx = random(0, width); // set initial position X
    this.posy = random(0, height); // set initial position Y
  }

  update() { // # function to update position
    var velx = random(-1,1); // random speed X
    var vely = random(-1,1); // random speed Y
    this.posx = this.posx + velx; // add speed X
    this.posy = this.posy + vely; // add speed Y
    
    // # so that the particles do not escape the sketch
    this.posx = constrain(this.posx, 0, width); // constrain posx on sketch width
    this.posy = constrain(this.posy, 0, height); // contrain posy on sketch height
  }

  collision(fixed) { // # function to check for collision
    for (var i = 0; i < fixed.length; i++) { // for every fixed particle
      // # calculate distance between [this] particle and every fixed particle
      let d = dist(this.posx, this.posy, fixed[i].posx, fixed[i].posy); 
      if (d < diameter) { // if collision
        return true; // collision() will evaluate to "true"
      }
    }
  }

  display() { // # function to display particle
    circle(this.posx, this.posy, diameter); // draw circle
  }
}

// ##### Main Sketch

// General Sketch Variables
let f = []; // array of fixed particles
let p = []; // array of moving particles
let diameter = 8; // diameter of all particles

// # Setup Function - [ called once at start ]
function setup() {
  createCanvas(500, 500);
  frameRate(600);
  
  // # create first fixed particle in the center of the sketch
  f[0] = new Particle(); 

  // # create 500 moving particles in the sketch
  for (var i = 0; i < 1000; i++) {
    p[i] = new Particle();
  }
}

// # Draw Loop - [ called every frame ]
function draw() {
  background(255);// Draw Background

  // # Display all fixed particles
  for (let i = 0; i < f.length; i++) {
    fill(255,0,0); // Red
    f[i].display(); // 
  }

  // # Display all moving particles
  for (let i = 0; i < p.length; i++) {
    fill(255,255,255); // White
    p[i].display();
  }

  // # Update and check for collisions
  for (let i = 0; i < p.length; i++) {  
    p[i].update(); // Update position
    if (p[i].collision(f)) { // p[i].collision(f) returns true if there is a collision
      f.push(p[i]); // copy collided particle into fixed particles
      p.splice(i, 1); // take out collided particle from moving particles
    }
  }
}