From fd32a3b1d023cc9a32e2043ac4682ddd5eeeeed1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matt=C3=A9o=20Delabre?= Date: Mon, 4 May 2020 19:03:50 +0200 Subject: [PATCH] Only attract to center when out of bounds + tuning --- boids.mjs | 10 +++++++--- draw.mjs | 4 ++-- index.mjs | 16 +++++++++------- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/boids.mjs b/boids.mjs index aa9e88b..9833820 100644 --- a/boids.mjs +++ b/boids.mjs @@ -4,7 +4,7 @@ const meanPos = new Vector(0, 0); const meanVel = new Vector(0, 0); const repelForce = new Vector(0, 0); -export const update = (boids, params, time) => +export const update = (boids, params, width, height, time) => { const boidsSize = boids.length; @@ -47,8 +47,12 @@ export const update = (boids, params, time) => .mul(params.centerAccel)); } - // Attract toward center of screen - me.vel.addMul(me.pos, -0.01); + // Attract toward center of screen if out of bounds + if (me.pos.x < width * -.4 || me.pos.x > width * .4 || + me.pos.y < height * -.4 || me.pos.y > height * .4) + { + me.vel.addMul(me.pos, -params.boundsAccel); + } // Repel away from close boids me.vel.add(repelForce.mul(params.repelAccel)); diff --git a/draw.mjs b/draw.mjs index 6f19008..e3d514d 100644 --- a/draw.mjs +++ b/draw.mjs @@ -10,7 +10,7 @@ const boidShape = [ const boidShapeSize = boidShape.length; const transformed = new Vector(0, 0); -export const fill = (activeBoids, params, ctx, width, height, center) => +export const fill = (activeBoids, params, width, height, ctx, center) => { const boidsSize = activeBoids.length; @@ -18,7 +18,7 @@ export const fill = (activeBoids, params, ctx, width, height, center) => // Draw each boid’s head following the angle of its course ctx.beginPath(); - ctx.fillStyle = 'black'; + ctx.fillStyle = params.color; for (let i = 0; i < boidsSize; ++i) { diff --git a/index.mjs b/index.mjs index 80e2ddc..ab4e04a 100644 --- a/index.mjs +++ b/index.mjs @@ -3,16 +3,18 @@ import * as boids from './boids.mjs'; import * as draw from './draw.mjs'; const params = { - centerAccel: 0.01, - repelAccel: 1, - matchAccel: 0.1, + centerAccel: 0.075, + repelAccel: 0.8, + matchAccel: 0.15, + boundsAccel: 0.01, maxSpeed: 300, closeDist: 20, - visibleDist: 80, + visibleDist: 60, radius: 10, + color: '#675148', }; const boidsCanvas = document.querySelector('#boids-canvas'); @@ -52,7 +54,7 @@ boidsCanvas.onclick = ev => { const pos = new Vector(ev.offsetX, ev.offsetY); pos.sub(center); - addBoids(pos, 50); + addBoids(pos, 100); }; let paused = false; @@ -68,8 +70,8 @@ const loop = time => const delta = (time - lastTime) / 1000; lastTime = time; - boids.update(activeBoids, params, delta); - draw.fill(activeBoids, params, boidsCtx, width, height, center); + boids.update(activeBoids, params, width, height, delta); + draw.fill(activeBoids, params, width, height, boidsCtx, center); if (!paused) {