boids/index.mjs

107 lines
1.8 KiB
JavaScript

import Vector from './vector.mjs';
import * as boids from './boids.mjs';
import * as draw from './draw.mjs';
const params = {
centerAccel: 0.075,
repelAccel: 0.8,
matchAccel: 0.15,
boundsAccel: 0.01,
maxSpeed: 300,
closeDist: 20,
visibleDist: 60,
radius: 10,
color: '#675148',
};
const boidsCanvas = document.querySelector('#boids-canvas');
const boidsCtx = boidsCanvas.getContext('2d');
let width = null;
let height = null;
let center = null;
const updateSize = () =>
{
width = window.innerWidth;
height = window.innerHeight;
center = new Vector(width / 2, height / 2);
boidsCanvas.width = width;
boidsCanvas.height = height;
};
updateSize();
window.onresize = updateSize;
const activeBoids = [];
const addBoids = (pos, count) =>
{
for (let i = 0; i < count; ++i)
{
activeBoids.push({
pos: pos.clone(),
vel: new Vector(Math.random(), Math.random()),
});
}
};
boidsCanvas.onclick = ev =>
{
const pos = new Vector(ev.offsetX, ev.offsetY);
pos.sub(center);
addBoids(pos, 100);
};
let paused = false;
let lastTime = null;
const loop = time =>
{
if (!lastTime)
{
lastTime = time;
}
const delta = (time - lastTime) / 1000;
lastTime = time;
boids.update(activeBoids, params, width, height, delta);
draw.fill(activeBoids, params, width, height, boidsCtx, center);
if (!paused)
{
requestAnimationFrame(loop);
}
};
const start = () =>
{
lastTime = null;
paused = false;
requestAnimationFrame(loop);
};
const pause = () =>
{
paused = true;
};
document.onvisibilitychange = () =>
{
if (document.visibilityState === 'visible')
{
start();
}
else
{
pause();
}
};
start();