Week4.png

link:https://editor.p5js.org/StonesGate604/sketches/ECVE0Y5fQ

Because I learned how to draw curves using vectors in p5js last time, I plan to do an assignment based on this method this week to consolidate my skills. My idea is to shoot out many different colored lines from the left side of the canvas to form a pattern.

To implement this, I primarily use classes to store the data for each line, or particle, including curvature (direction), color, vector, and so on. This has the advantage of allowing me to assign this data directly to the class constructor when it's created, and then call its update function in the draw function. This makes the code more concise and manageable.

class Agent {
  constructor(x0, y0, number) {
    this.p = createVector(x0, y0);
    this.direction = 1;
    this.color = colors256[number % 256];
    this.scale = 5;
    this.strokeWidth = 5 + 5 * sin(frameCount);
    this.pOld = createVector(this.p.x, this.p.y);
    this.step = 1;
  }

  update() {
    this.p.x +=
      this.direction *
      vector_field(this.p.x, this.p.y, this.scale).x *
      this.step;
    this.p.y +=
      this.direction *
      vector_field(this.p.x, this.p.y, this.scale).y *
      this.step;

    strokeWeight(this.strokeWidth);
    if (frameCount % 20 == 0) {
      noStroke();
      fill(this.color);
      circle(this.p.x, this.p.y, 16);
      this.pOld.set(this.p);
    }
  }
}

When processing the vector field and determining the direction of the line, I used trigonometric functions to make the line undulate regularly, and added random numbers using noise. However, this formula will eventually make the curve flatten as the frameCount increases.

// caculate the direction of every particle
function vector_field(x, y, myScale) {
  x = map(x, 0, width, -myScale, myScale);
  y = map(y, 0, height, -myScale, myScale);
  let k1 = 5;
  let k2 = 3;
  let v = sin(k2 * x) - cos(k1 * x) + map(noise(x, y), 0, 1, -1, 1);
  return createVector(1, v);
}