2020-05-04 15:17:55 +00:00
|
|
|
import Vector from './vector.mjs';
|
|
|
|
import * as boids from './boids.mjs';
|
|
|
|
import * as draw from './draw.mjs';
|
|
|
|
|
|
|
|
const params = {
|
2020-05-04 17:03:50 +00:00
|
|
|
centerAccel: 0.075,
|
|
|
|
repelAccel: 0.8,
|
|
|
|
matchAccel: 0.15,
|
|
|
|
boundsAccel: 0.01,
|
2020-05-04 15:17:55 +00:00
|
|
|
|
|
|
|
maxSpeed: 300,
|
|
|
|
|
|
|
|
closeDist: 20,
|
2020-05-04 17:03:50 +00:00
|
|
|
visibleDist: 60,
|
2020-05-04 15:17:55 +00:00
|
|
|
|
2020-05-04 16:29:00 +00:00
|
|
|
radius: 10,
|
2020-05-04 17:03:50 +00:00
|
|
|
color: '#675148',
|
2020-05-04 15:17:55 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
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 = [];
|
|
|
|
|
2020-05-04 16:46:26 +00:00
|
|
|
const addBoids = (pos, count) =>
|
2020-05-04 15:17:55 +00:00
|
|
|
{
|
2020-05-04 16:46:26 +00:00
|
|
|
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);
|
2020-05-04 17:03:50 +00:00
|
|
|
addBoids(pos, 100);
|
2020-05-04 16:46:26 +00:00
|
|
|
};
|
2020-05-04 15:17:55 +00:00
|
|
|
|
2020-05-04 16:37:33 +00:00
|
|
|
let paused = false;
|
2020-05-04 15:17:55 +00:00
|
|
|
let lastTime = null;
|
|
|
|
|
|
|
|
const loop = time =>
|
|
|
|
{
|
|
|
|
if (!lastTime)
|
|
|
|
{
|
|
|
|
lastTime = time;
|
|
|
|
}
|
|
|
|
|
|
|
|
const delta = (time - lastTime) / 1000;
|
|
|
|
lastTime = time;
|
|
|
|
|
2020-05-04 17:03:50 +00:00
|
|
|
boids.update(activeBoids, params, width, height, delta);
|
|
|
|
draw.fill(activeBoids, params, width, height, boidsCtx, center);
|
2020-05-04 15:17:55 +00:00
|
|
|
|
2020-05-04 16:37:33 +00:00
|
|
|
if (!paused)
|
|
|
|
{
|
|
|
|
requestAnimationFrame(loop);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const start = () =>
|
|
|
|
{
|
|
|
|
lastTime = null;
|
|
|
|
paused = false;
|
2020-05-04 15:17:55 +00:00
|
|
|
requestAnimationFrame(loop);
|
|
|
|
};
|
|
|
|
|
2020-05-04 16:37:33 +00:00
|
|
|
const pause = () =>
|
|
|
|
{
|
|
|
|
paused = true;
|
|
|
|
};
|
|
|
|
|
|
|
|
document.onvisibilitychange = () =>
|
|
|
|
{
|
|
|
|
if (document.visibilityState === 'visible')
|
|
|
|
{
|
|
|
|
start();
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
pause();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
start();
|