DISK 06 / BOIDS
a flock of birds that fly, which you cannot: nobody leads it. every bird follows three rules, keep a little away from the ones closest, fly the way your neighbours fly, drift towards the middle of them, and the flock comes out of that by itself
function setup(ctx, W, H) {
var k = { n: 150, sep: 0.06, align: 0.05, coh: 0.004 }
/*TWEAK*/
var b = []
for (var i = 0; i < k.n; i++) b.push({ x: Math.random() * W, y: Math.random() * H, vx: Math.random() * 2 - 1, vy: Math.random() * 2 - 1 })
ctx.fillStyle = '#0a0c14'
ctx.fillRect(0, 0, W, H)
return { k: k, b: b }
}
function update(state, t, W, H) {
var k = state.k, b = state.b, n = b.length
for (var i = 0; i < n; i++) {
var a = b[i], sx = 0, sy = 0, ax = 0, ay = 0, cx = 0, cy = 0, near = 0
for (var j = 0; j < n; j++) {
if (i === j) continue
var o = b[j], dx = o.x - a.x, dy = o.y - a.y
if (dx > W / 2) dx -= W; if (dx < -W / 2) dx += W
if (dy > H / 2) dy -= H; if (dy < -H / 2) dy += H
var d2 = dx * dx + dy * dy
if (d2 > 2500) continue
near++
ax += o.vx; ay += o.vy; cx += dx; cy += dy
if (d2 < 200) { sx -= dx / (d2 + 1) * 20; sy -= dy / (d2 + 1) * 20 }
}
if (near) {
a.vx += (ax / near - a.vx) * k.align + cx / near * k.coh + sx * k.sep
a.vy += (ay / near - a.vy) * k.align + cy / near * k.coh + sy * k.sep
}
var sp = Math.hypot(a.vx, a.vy) || 1
var lim = Math.min(3, Math.max(1.4, sp))
a.vx = a.vx / sp * lim; a.vy = a.vy / sp * lim
}
for (var m = 0; m < n; m++) {
var p = b[m]
p.x = (p.x + p.vx + W) % W
p.y = (p.y + p.vy + H) % H
}
}
function render(ctx, state, t, W, H) {
ctx.fillStyle = 'rgba(10,12,20,0.3)'
ctx.fillRect(0, 0, W, H)
var b = state.b
for (var i = 0; i < b.length; i++) {
var p = b[i], a = Math.atan2(p.vy, p.vx)
ctx.fillStyle = 'hsl(' + ((a * 180 / Math.PI + 360 + t * 0.5) % 360 | 0) + ',70%,65%)'
ctx.beginPath()
ctx.moveTo(p.x + Math.cos(a) * 7, p.y + Math.sin(a) * 7)
ctx.lineTo(p.x + Math.cos(a + 2.5) * 4, p.y + Math.sin(a + 2.5) * 4)
ctx.lineTo(p.x + Math.cos(a - 2.5) * 4, p.y + Math.sin(a - 2.5) * 4)
ctx.fill()
}
}