xxxxxxxxxx
89
var attractors = [];
var fishies = [];
function setup() {
createCanvas(400, 400);
for (var i = 0; i < 700 ; i++){
fishies.push(new fish(random(width),random(height)));
}
}
function mousePressed(){
attractors.push(createVector(mouseX, mouseY));
}
function draw() {
background(51);
stroke(255);
strokeWeight(8);
for (var i = 0; i < attractors.length; i++){
stroke(255,0,0);
point(attractors[i].x, attractors[i].y);
var r = floor(random(4));
switch (r) {
case 0:
attractors[i].x = attractors[i].x + random(1,4);
break;
case 1:
attractors[i].x = attractors[i].x - random(1,4);
break;
case 2:
attractors[i].y = attractors[i].y + random(1,4);
break;
case 3:
attractors[i].y = attractors[i].y - random(1,4);
break;
}
}
for (var i = 0; i < fishies.length; i++){
var fish = fishies[i]
for (var j = 0; j < attractors.length; j++){
fish.attracted(attractors[j]);
}
fish.show();
fish.update();
}
}
function fish(x,y){
this.pos = createVector(x,y);
this.vel = p5.Vector.random2D();
this.acc = createVector();
this.update = function(){
this.vel.add(this.acc);
this.vel.limit(2);
this.pos.add(this.vel);
this.acc.mult(0);
}
this.show = function(){
stroke(255);
strokeWeight(3);
point(this.pos.x, this.pos.y);
}
this.attracted = function(target){
var force = p5.Vector.sub(target, this.pos);
var d = force.mag();
d = constrain(d, 2, 25);
var G = 10;
var strength = G / (d * d);
force.setMag(strength);
if (d < 20){
force.mult(-5);
}
this.acc.add(force);
}
}