Skip to content

Particle swarm

Move the mouse to have particles swarms around it. Hold down mouse button to hold the particles in place.

A swarm of particles chasing down the mouse cursor

let a = []
function setup() {
  createCanvas(windowWidth, windowHeight);
  a = Array(100).fill().map(c)
}
function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

function c() {
  let x = random(width)
  let y = random(height)
  let vx = 0
  let vy = 0
  return function() {
    let d = dist(x, y, mouseX, mouseY) ** 0.5 + 1
    push()
    translate(x, y)
    rotate(atan2(y - mouseY, x - mouseX))
    rect(0, 0, d + 10, 10)
    pop()

    vx += (mouseX - x) / (d) / 20 * !mouseIsPressed + random(-1, 1) * 0.2
    vy += (mouseY - y) / (d) / 20 * !mouseIsPressed + random(-1, 1) * 0.2
    vx *= 0.97
    vy *= 0.97
    x += vx
    y += vy
  }
}

function draw() {
  background(220);
  rectMode(CENTER)
  for (let i of a) i();
}

(Originally seen at https://editor.p5js.org/bojidar-bg/sketches/YJZPVjw-e)

Experiments tagged p5 (77/85)

Experiments tagged interactive (25/26)

Experiments on this site (77/85)