رفتن به محتواCREATIVE·CODE·ART
160
1
10
5
p5.js

Firefly Swarm

A swarm of fireflies chasing one lantern. The lantern is your finger — lead them around, watch them stream and gather. Hands off, it wanders and they follow.

مجوز: CC BY-NC-SA 4.0: ریمیکس با ذکر نام، غیرتجاری، با همین مجوز

دیدن کد
// Firefly Swarm — a p5.js swarm that follows your hand
// A cloud of fireflies chases a lantern. Touch and the lantern is your finger;
// leave it and the lantern wanders by itself. Palette: charcoal, bone, signal orange.
// Site sliders: Swarm · Follow · Trails · Sparkle — read through params.*

const BONE = [233, 229, 218];
const ORANGE = [255, 180, 84];
const BG = [13, 13, 18];

let flies = [];

function setup() {
  createCanvas(windowWidth, windowHeight);
  background(...BG);
}

function lantern() {
  if (mouseX > 0 && mouseY > 0) return [mouseX, mouseY];
  return [
    width / 2 + cos(frameCount * 0.006) * width * 0.26 + cos(frameCount * 0.0163) * width * 0.07,
    height / 2 + sin(frameCount * 0.0083) * height * 0.24
  ];
}

function draw() {
  noStroke();
  fill(BG[0], BG[1], BG[2], params.trails ?? 10);
  rect(0, 0, width, height);

  const want = round(params.swarm ?? 160);
  while (flies.length < want) {
    flies.push({
      x: random(width), y: random(height),
      vx: random(-1, 1), vy: random(-1, 1),
      seed: random(1000), orange: random() < 0.72
    });
  }
  if (flies.length > want) flies.splice(0, flies.length - want);

  const L = lantern();
  const follow = (params.follow ?? 1) * 0.028;
  const sparkle = params.sparkle ?? 5;

  for (const f of flies) {
    const wa = noise(f.seed, frameCount * 0.004) * TWO_PI * 2;
    f.vx += cos(wa) * 0.06;
    f.vy += sin(wa) * 0.06;
    const dx = L[0] - f.x, dy = L[1] - f.y;
    const d = max(30, Math.hypot(dx, dy));
    f.vx += (dx / d) * follow * 10 * (d > 130 ? 1 : 0.25);
    f.vy += (dy / d) * follow * 10 * (d > 130 ? 1 : 0.25);
    if (d < 46) { f.vx -= (dx / d) * 0.22; f.vy -= (dy / d) * 0.22; }
    f.vx *= 0.94; f.vy *= 0.94;
    f.x += f.vx; f.y += f.vy;

    const col = f.orange ? ORANGE : BONE;
    const tw = 0.6 + 0.4 * sin(frameCount * 0.09 + f.seed * 20);
    noStroke();
    fill(col[0], col[1], col[2], 46 * tw);
    ellipse(f.x, f.y, 6 + sparkle * 1.7);
    fill(col[0], col[1], col[2], 225 * tw);
    ellipse(f.x, f.y, 2.4);
  }

  noStroke();
  fill(255, 218, 155, 240);
  ellipse(L[0], L[1], 7);
}

function keyPressed() {
  if (key === 's' || key === 'S') saveCanvas('firefly-swarm', 'png');
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
  background(...BG);
}