Boids

by ElijahCirioli

HTML

<canvas id="myCanvas" width="1000" height="700"></canvas>

CSS

#myCanvas {
	border: 5px solid #3A5032;
}

JavaScript

//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; //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 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
		
		//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;
		
		//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 =...