boids/index.mjs

67 lines
1.2 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: 5,
};
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),
});
}
let lastTime = null;
const loop = time =>
{
if (!lastTime)
{
lastTime = time;
}
const delta = (time - lastTime) / 1000;
lastTime = time;
boids.update(activeBoids, params, delta);
draw.boids(activeBoids, params, boidsCtx, width, height, center);
requestAnimationFrame(loop);
};
requestAnimationFrame(loop);