//setup canvas
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
//initialize variables
var boids = []; //all the boids
var distance = 100; //the radius of the boid's neighborhood (px)
var viewAngle = 5 * Math.PI / 3; //the viewing angle of the boid's neighborhood (radians)
var boidCount = 70; //how many boids to create
var speed = 4.0; //how fast the boids move
var showDebug = false; //show view angle and rays for one boid
var mouseMode = 0; //0 = draw boids, 1 = scatter
var mouseDown = false; //is the mouse being pressed down
var pred = new Predator(0, 0, 0); //the predator to scatter the boids away from
//define weights for the three rules
var separationWeight = 1;
var alignmentWeight = 1;
var cohesionWeight = 1;
//how much the rules affect the current velocity
var inertia = 0.5;
//define a boid
function Boid(x, y, velX, velY) {
this.x = x;
this.y = y;
this.direction = 0;
this.velX = velX;
this.velY = velY;
this.neighborhood = [];
}
//define a predator
function Predator(x, y, life) {
this.x = x;
this.y = y;
this.life = life;
}
//game cycle
function update() {
moveBoids();
draw();
}
//update the velocity vectors of all boids and move
function moveBoids() {
for (var i = 0; i < boids.length; i++) {
var b = boids[i];
b.neighborhood = getNeighborhood(b); //get all boids within Distance radius and viewAngle
//gather the vectors from the three rules
var vec1 = b.separation();
var vec2 = b.alignment();
var vec3 = b.cohesion();
var vec4 = b.guidance();
//add the vectors together and multiply weights
b.velX += inertia * ((vec1[0] * separationWeight) + (vec2[0] * alignmentWeight) + (vec3[0] * cohesionWeight) + vec4[0]);
b.velY += inertia * ((vec1[1] * separationWeight) + (vec2[1] * alignmentWeight) + (vec3[1] * cohesionWeight) + vec4[1]);
//normalize the speed to what it should be
var nomalizedVector = normalize([b.velX, b.velY], speed);
b.velX =...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.