boids
by dirkk0
JavaScript
var width = 200;
var height = 140;
var paper = Raphael(10, 50, 320, 200);
// var circle = paper.circle(50, 40, 10);
var random = function(maxNum) {
return Math.ceil(Math.random() * maxNum);
};
var Boid = function(x, y, size) {
this.x = x;
this.y = y;
this.xVelocity = 1;
this.yVelocity = -1;
this.circle = paper.circle(x, y, size).attr({
fill: '#FF0000'
});
};
Boid.prototype.move = function() {
this.x += this.xVelocity;
this.y += this.yVelocity;
var border = 5;
if (this.x <= border || this.x >= width - border) {
this.x -= this.xVelocity;
this.x = Math.max(this.x, border);
this.x = Math.min(this.x, width - border);
this.xVelocity = -this.xVelocity;
this.x += this.xVelocity;
}
if (this.y <= border || this.y >= height - border) {
this.y -= this.yVelocity;
this.y = Math.max(this.y, border);
this.y = Math.min(this.y, height - border);
this.yVelocity = -this.yVelocity;
this.y += this.yVelocity;
}
this.circle.translate(this.xVelocity, this.yVelocity);
}
var boids = [];
var numBoids = 20;
for (var i = 0; i < numBoids; i++) {
boids.push(new Boid(random(width), random(height), 5));
};
function moveBoids() {
for (var i = 0; i < numBoids; i++) {
// boids[i].moveWith(boids, 300);
// boids[i].moveCloser(boids, 300);
// boids[i].moveAway(boids, 15);
}
for (var i = 0; i < numBoids; i++) {
boids[i].move();
}
setTimeout(arguments.callee, 50);
// setTimeout(moveBoids, 50);
};
moveBoids();