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 = {
|
|
|
|
centerAccel: 0.01,
|
|
|
|
repelAccel: 1,
|
|
|
|
matchAccel: 0.1,
|
|
|
|
|
|
|
|
maxSpeed: 300,
|
|
|
|
|
|
|
|
closeDist: 20,
|
|
|
|
visibleDist: 80,
|
|
|
|
|
2020-05-04 16:29:00 +00:00
|
|
|
radius: 10,
|
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 = [];
|
|
|
|
|
|
|
|
for (let i = 0; i < 300; ++i)
|
|
|
|
{
|
|
|
|
activeBoids.push({
|
|
|
|
pos: new Vector(200 + (i % 2) * (-400), 0),
|
|
|
|
vel: new Vector(Math.random() * 100, Math.random() * 100),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
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;
|
|
|
|
|
|
|
|
boids.update(activeBoids, params, delta);
|
2020-05-04 16:29:00 +00:00
|
|
|
draw.fill(activeBoids, params, boidsCtx, width, height, 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();
|