105 lines
1.7 KiB
JavaScript
105 lines
1.7 KiB
JavaScript
import Vector from './vector.mjs';
|
|
import * as boids from './boids.mjs';
|
|
import * as draw from './draw.mjs';
|
|
|
|
const params = {
|
|
centerAccel: 0.01,
|
|
repelAccel: 1,
|
|
matchAccel: 0.1,
|
|
|
|
maxSpeed: 300,
|
|
|
|
closeDist: 20,
|
|
visibleDist: 80,
|
|
|
|
radius: 10,
|
|
};
|
|
|
|
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, 50);
|
|
};
|
|
|
|
let paused = false;
|
|
let lastTime = null;
|
|
|
|
const loop = time =>
|
|
{
|
|
if (!lastTime)
|
|
{
|
|
lastTime = time;
|
|
}
|
|
|
|
const delta = (time - lastTime) / 1000;
|
|
lastTime = time;
|
|
|
|
boids.update(activeBoids, params, delta);
|
|
draw.fill(activeBoids, params, boidsCtx, width, height, 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();
|