Back to Parent

// P5.js Code

let eyes = [];

function setup() {
  createCanvas(windowWidth, windowHeight);
  background(0);
  for (let i = 0; i < 50; i++) {
    let size = random(20, 100);
    let x = random(size, width - size);
    let y = random(size, height - size);
    let eye = new Eye(x, y, size);
    for (let j = 0; j < eyes.length; j++) {
      let d = dist(x, y, eyes[j].x, eyes[j].y);
      if (d < size + eyes[j].size) {
        x = random(size, width - size);
        y = random(size, height - size);
        eye.x = x;
        eye.y = y;
        j = -1;
      }
    }
    eyes.push(eye);
  }
  serial = new p5.SerialPort();
  serial.open("/dev/ttyUSB0");
  serial.on("data", serialEvent);
}

function serialEvent() {
  let data = serial.readStringUntil("\n");
  if (data) {
    let location = split(data, ",");
    if (location.length == 2) {
      let x = map(location[0], 0, 1023, 0, width);
      let y = map(location[1], 0, 1023, 0, height);
      for (let i = 0; i < eyes.length; i++) {
        eyes[i].update(x, y);
      }
    }
  }
}

function draw() {
  for (let i = 0; i < eyes.length; i++) {
    eyes[i].display();
  }
}

class Eye {
  constructor(x, y, size) {
    this.x = x;
    this.y = y;
    this.size = size;
    this.pupilSize = this.size / 3;
    this.pupilX = this.x;
    this.pupilY = this.y;
    this.angle = 0;
  }

  update(x, y) {
    let d = dist(x, y, this.x, this.y);
    let maxDist = this.size / 2 - this.pupilSize / 2;
    let mappedDist = map(d, 0, maxDist, 0, 1);
    let angle = atan2(y - this.y, x - this.x);
    angle = constrain(angle, -PI / 4, PI / 4);
    this.angle = lerp(this.angle, angle, 0.1);
    this.pupilX = this.x + cos(this.angle) * mappedDist * maxDist;
    this.pupilY = this.y + sin(this.angle) * mappedDist * maxDist;
  }

  display() {
    noStroke();
    fill(255);
    ellipse(this.x, this.y, this.size);
    fill(0);
    ellipse(this.pupilX, this.pupilY, this.pupilSize);
  }
}
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0